get date from database to date field on editing - asp.net

I have 2 pages. A create page and an edit page. When I choose a date on the create page and submit it, it all goes right. But when I read the date out the database and set it in the input field, it won't display the date.
date field in create & edit page:
<div class="form-group">
#Html.LabelFor(model => model.activity.Date, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.activity.Date, new { htmlAttributes = new { #class = "form-control", onclick = "this.showPicker()", required = "required" } })
#Html.ValidationMessageFor(model => model.activity.Date, "", new { #class = "text-danger" })
</div>
[DataType(DataType.Date)]
public DateTime Date { get; set; }
model.Date = Convert.ToDateTime(dt.Rows[0][2]);
this what i get in edit page
what i want:

Related

Multiple selection in Dropdown list in razor not working

I am working on Asp.net core project.
I want to Bind List to #Html.DropDownListFor in razor view for multiple selection with checkboxes.
I have tried various codes but that didn't work.
I am getting result like this.
My Model List is :
public List<SelectListItem> DDLCOO { get; set; }
And I have tried various Razor codes but nothing worked:
#Html.DropDownListFor(model => model.COOId, new SelectList(Model.DDLCOO, "Value", "Text", Model.DDLCOO), new { #class = "form-control multiselect-dropdown", #multiple = "true", #id = "DDLCOO" })
#Html.DropDownListFor(model => model.COOId, Model.DDLCOO, new { #class = "form-control multiselect-dropdown", #id = "DDLCOO", multiple = "true" })
#Html.DropDownListFor(model => Model.COOId, Model.DDLCOO, new { #class = "form-control", #id = "DDLCOO", multiple = "multiple"})
#Html.ListBoxFor(model => model.COOId, Model.DDLCOO, new { #class = "form-control", #id = "DDLCOO" })

Accurate way of passing data controller to view ASP.NET MVC

In my application, to load some data to the view (combo boxes) I have been using TempData. I want to know if it is okay to use TempData for that purpose?
My current code is here; first I called data to a list in controller:
List<Request_Types> RequestTyleList = db.Request_Types.Where(r => r.Status == true).ToList();
List<SelectListItem> ReqTypeDropDown = RequestTyleList.Select(r => new SelectListItem { Text = r.Request_Type, Value = r.Id.ToString() }).ToList();
Then I am assigning this data to TempData:
TempData["RequestTyleList"] = ReqTypeDropDown;
In the view I called that temp data and assigning to the combo box
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> ReqType = (List<SelectListItem>)TempData.Peek("RequestTyleList");
}
-----------------
<div class="form-group row">
#Html.LabelFor(model => model.ReqType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.ReqType, ReqTypes, "Select Request Type", new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.ReqType, "", new { #class = "text-danger" })
</div>
</div>
If I want to access those same data in Edit, I again create a list and putting data to the list and transfer to TempData and again call the same data from the view. Still I have 5 to 8 items of data on the list, I want to know when there are 100 items of data in TempData, will my system get slow? Are there any potential performance issues?
While surfing this on the internet, I got that same will do in the Sessions, but I don't know will it be suitable for this? Or else is there any good way to do this without dropping any performance of the system, like in one controller if I call and stores data, I can access those data from any view.
#smc developments, please use below Model and html markup to show dropdown list for users
public class User
{
public int SelectedUserId{get;set;}
public IEnumerable<SelectListItem> Users { get; set; }
}
#Html.DropDownListFor(x => Model.SelectedUserId, new SelectList(Model.Users, "Value", "Text"), htmlAttributes: new { #class = "form-control", id = "User"})

failed to execute: javax.ws.rs.NotFoundException:

Hello i'm trying to consume rest web service from jee application to asp.net
when i copy the url it work perfectly but when i excute it from the app the url changes specifically the dates .
Example of the erorr :
22:03:32,629 WARN [org.jboss.resteasy.core.ExceptionHandler] (default
task-69) failed to execute: javax.ws.rs.NotFoundException: Could not
find resource for full path:
http://localhost:18080/PiDev-web/rest/absence/creates/aaaqwqwq/07/11/2018%2000:00:00/07/11/2018%2000:00:00
[JEE app]
here's my service :
#Override
public void createAbsence(Absence e) {
EmployeService ee =new EmployeService();
ConnectedUser emp = em.find(ConnectedUser.class, 1);
System.out.println("Service Done 0 !!!");
e.setIdEmploye(emp.getId());
e.setLogin(emp.getLogin());
e.setJustifie(false);
//e.setEmploye(UserConnected);
em.persist(e);
System.out.println("Service Done !!!");
}
and myBean:
#POST
#Path("/creates/{cause}/{dd}/{df}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response serviceCreates(#PathParam(value = "cause") String cause,#PathParam(value = "dd") String dd,#PathParam(value = "df") String df) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date dated=new Date();
Date datef=new Date();
try {
dated = dateFormat.parse(dd);
datef = dateFormat.parse(df);
System.out.println(dated);
} catch (ParseException e) {
e.printStackTrace();
}
return Response.status(Status.ACCEPTED).entity(absenceService.createAbsence(new Absence(cause,dated,datef))).build();
}
[Asp.Net app]
Controller :
[HttpPost]
public ActionResult Create(absence abs)
{
try
{
HttpClient Client = new System.Net.Http.HttpClient();
Console.WriteLine(abs.dateDebut);
Client.BaseAddress = new Uri("http://localhost:18080/PiDev-web/rest/absence/");
Client.PostAsJsonAsync<absence>("creates/" + abs.cause + "/" + abs.dateDebut + "/" + abs.dateFin, abs);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
and my view :
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/backLayout.cshtml";
}
#model ProjectWeb.Models.absence
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Add Absence</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.cause, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cause, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cause, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateDebut, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateDebut, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateDebut, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateFin, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateFin, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateFin, "", new { #class = "t-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
i'm not familiar with date formats so if you are familiar please help me
The problem in your url that you use slash to separate year, month and day. Actually url use slash to separate part of path, so you have to not use slash except separate element of path.
For sending date it's better to use ISO format. Long story short you write date from biggest to lowest values and separate them using dash (year-month-dayThour:minutes:seconds) example
date time 2018-11-07T22:30:33
only date 2018-11-07
Rewrite your resource like this:
#POST
#Path("/creates/{cause}/{dd}/{df}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response serviceCreates(#PathParam(value = "cause") String cause,#PathParam(value = "dd") LocalDate dd,#PathParam(value = "df") LocalDate df) {
return Response.status(Status.ACCEPTED).entity(absenceService.createAbsence(new Absence(cause,dd,df))).build();
}
and try to invoke:
http://localhost:18080/PiDev-web/rest/absence/creates/aaaqwqwq/2018-11-07/2018-11-07

Issue with DateTime Property

Here is my property in my model:
[Display(Name = "Date / Time:")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy HH:mm}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DayTime { get; set; }
For my application it is necessary to include the time.
Here is my .cshtml
<div class="form-group">
#Html.LabelFor(model => model.DayTime, htmlAttributes: new { #class = "control-label col-md-2 required" })
<div class="col-md-10">
#Html.EditorFor(model => model.DayTime, new { htmlAttributes = new { #class = "form-control datepicker" } })
#Html.ValidationMessageFor(model => model.DayTime, "", new { #class = "text-danger" })
</div>
</div>
I am using jQuery Datepicker.
When the user initially goes to the Create page, I have it setup so that it will automatically have today's date and current time already in the EditorFor as so:
public ActionResult Create()
{
DailySummary daily = new DailySummary();
daily.DayTime = DateTime.Now;
return View(daily);
}
Now that all works fine, until I want to change the date and time... I am able to change the Date portion but I am unable to add the HH:mm part of the DateTime... like the EditorFor isn't allowing me to space from the Date portion to enter the time.
How do I fix this so that I can enter the time portion along with the date?
After searching around I found Bootstrap 3 Datepicker v4
I went into Nuget and downloaded the .CSS version of Bootstrap.v3.Datetimepicker.CSS.
After referencing the newly downloaded files in my _Layout View I followed the simple instructions in the link given above, and it works like a charm.

Why is my date control empty when page loads?

My Date control is always empty when the page loads.
Why is that?
There is data in the database for that control.
<div class="form-group">
#Html.LabelFor(model => model.StartDate, new { #class = "control- label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.StartDate, new { type = "Date" })
#Html.ValidationMessageFor(model => model.StartDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.EndDate, new { type = "Date" })
#Html.ValidationMessageFor(model => model.EndDate)
</div>
</div>
As noted by #Coulton, make sure you're actually populating your model's StartDate and EndDate properties on your controller before rendering the page. Also if you use the [DataType(DataType.Date)] flag on your class you could discard the TextBoxFor helper and instead used the EditorFor helper.
Examples for populating the data attributes before a Create or an Edit view (Which seems to be the view you're trying to build there):
Controller.cs, ganho.Data is a DateTime attribute with a [DataType(DataType.Date)] flag
[HttpGet]
public ActionResult Edit(int? id)
{
// Omitted code
var result = from ganho in db.Ganhos
where ganho.GanhoID == id.Value
where ganho.Usuario.Id == user.Id
select new GanhoEditViewModel
{
GanhoID = ganho.GanhoID,
Valor = ganho.Valor,
Comentario = ganho.Comentario,
Data = ganho.Data,
Descricao = ganho.Descricao,
Tipo = ganho.Tipo
};
if (result.Count() < 1)
{
// 404, no such item exists
return HttpNotFound();
}
return View(result.Single());
}
Edit.chtml
<!-- Hidden Code, not relevant to the question -->
<div class="form-group">
#Html.LabelFor(model => model.Data, htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.Data, new { htmlAttributes = new { #class = "form-control", #id = "dataInput"} })
#Html.ValidationMessageFor(model => model.Data, "", new { #class = "text-danger"})
</div>
</div>
In case you're setting up for a Create view, you can initialize the field like this:
Controller.cs, ganho.Data is my DateTime attribute which the user will display a placeholder data.
[HttpGet]
public ActionResult Create()
{
var model = new Ganho()
{
// ...
Data = DateTime.Now, // Using the current date and time as a placeholder
// ...
};
return View(model);
}
Please note that in all examples I'm using Strongy Typed views!

Resources