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!
Related
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:
I am working on a tutorial from the Microsoft website with the end result like this image:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-5/_static/image4.png
The price textbox in the View is:
<div class="form-group">
#Html.LabelFor(model => model.AlbumToEdit.Price, "Price", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AlbumToEdit.Price)
#Html.ValidationMessageFor(model => model.AlbumToEdit.Price)
</div>
</div>
Which renders as:
<input class="text-box single-line" id="AlbumToEdit_Price" name="AlbumToEdit.Price" type="text" value="9.99">
If I inspect the HTML via DevTools and add the below:
<input id="AlbumToEdit_Price" name="AlbumToEdit.Price" type="hidden" value="33.33">
And click the Save button to save the album details, the binding process is taking the 33.33 in consideration, regardless what I insert in the Price textbox, probably because both <input> tags share the same id and name.
How can I avoid this?
Controller code follows:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AlbumToEditViewModel postedViewModel)
{
if (ModelState.IsValid)
{
db.Entry(postedViewModel.AlbumToEdit).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
AlbumToEditViewModel albumToEditViewModel = new AlbumToEditViewModel
{
AlbumToEdit = postedViewModel.AlbumToEdit,
Artists = new SelectList(db.Artists, "ArtistId", "Name", postedViewModel.AlbumToEdit.ArtistId),
Genres = new SelectList(db.Genres, "GenreId", "Name", postedViewModel.AlbumToEdit.GenreId)
};
return View(albumToEditViewModel);
}
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
I’m using BeginForm to pass model data (i.e. last_coffe_time) which works fine. However I also wanted to pass to controller ClientDateTime value stored in hidden field which is not a part of the model.
I don’t know how do do it, at best I can pass ClientDateTime as static string but I can't figure out how to dynamically read hidden field for value and pass that value to controller.
Someone please help. Thank you
View:
#model SleepNotes.Models.Diary
#using (Html.BeginForm("Edit", "Diary", new { ClientDateTime = "ClientDateTime" }, FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.Hidden("ClientDateTime", new { id = "ClientDateTime" })
<div class="form-group">
#Html.LabelFor(model => model.last_coffe_time, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.last_coffe_time, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.last_coffe_time, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<!--Set ClientDateTime-->
<script>
var a = new Date()
var month = a.getMonth() + 1;
document.getElementById('ClientDateTime').value = a.getDate() + "/" + month + "/" + a.getFullYear() + " " + a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,last_coffe_time")] Diary Diary, string ClientDateTime)
{
if (ModelState.IsValid)
{
//ClientDateTime from view ...do something here
db.Entry(Diary).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index", "Dashboard");
}
return View(Diary);
}
Remove the new { ClientDateTime = "ClientDateTime" } from the BeginForm() method so the vale is not added as a route parameter (and therefore not bound to your string ClientDateTime parameter in the Edit() method.
Side note: since your wanting to submit a DateTime value, your parameter should be DateTime ClientDateTime (not string) and your script can be simplified to
document.getElementById('ClientDateTime').value = new Date().toISOString();
There are some solutions,
I suggest you to have a ModelView between your Model and View. That
modalview should have the ClientDateTime.
You can use ajax post and send 2 parameters (yourmodal, string) to controller or you
can pass the ClientDateTime as querystring. There are lots of
examples about it.
Hope helps.
I'm using ASP.NET MVC 4 for editing model objects via Html.BeginForm(). The issue is when I pass the model object to be edited, the only part of view that renders properly is the OK button.
Html.TextBoxFor() does not show the input textbox in the View or shown as text when in fieldset, even if I added '#' before it.
Here's the code:
AddEdit.cshtml
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>AddEdit</title>
</head>
<body>
<div>
#using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
<fieldset>
#Html.TextBoxFor(model => model.Hero.Name);
<input type="submit" value="OK" />
</fieldset>
}
</div>
</body>
</html>
And here's my controller class:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public string GetData()
{
return JsonConvert.SerializeObject(new {data = new HeroStorage().GetAllViewModels()});
}
[HttpPost]
public void Edit(AddEditViewModel model)
{
new HeroStorage().Update(model.Hero);
RedirectToAction("Index");
}
//RETURNS THE VIEW
[HttpGet]
public ActionResult Edit(int ID)
{
return View("AddEdit", new AddEditViewModel(){Hero = new HeroStorage().GetByID(ID), Studios = new StudioStorage().GetAll()});
}
}
This is happening because after updating the content in the Post Method of Edit, you are redirecting to INDEX which in return do not pass any model to the view so, the #Html.TextBoxFor(m => m.Hero.Name) is empty.
UPDATE:
Eventually the problem was fixed by changing TextBoxFor to EditorFor
I would post this as a comment, but it wouldn't be readable/etc which i think you could make great use of. However, here is some of the Auto generated code from the framework:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Pot</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.TrailerID)
#Html.HiddenFor(model => model.Pot)
<div class="form-group">
#Html.LabelFor(model => model.Capacity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Capacity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Capacity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
The main things to look here for are:
the use of #Html.EditorFor(...
an AntiForgeryToken
I'm using EF
The [HttpPost] method for the Edit:
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "TrailerID,Pot,Capacity,Comments")] tbl_Pot tbl_Pot)
{
if (ModelState.IsValid)
{
db.Entry(tbl_Pot).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tbl_Pot);
}
PS/Disclaimer: Please do not worry about the naming of my tbl/entries, as these refer to a fuel system, not any other kind of 'Pot'
Which browser is this?
Your code seems to work in IE 11 and Chrome - i.e. I've just copy/paste it and received the text box. However, I'd like to mention the following:
Loose the semi-colon after the #Html.TextBoxFor(model => model.Hero.Name).
You don't need that in a Razor expression.
#Html.TextBoxFor(model => model.Hero.Name) refers to unknown object named "model".
Remember that the property, which refers to the actual model is
Model, not "model". I'd recommend changing
#Html.TextBoxFor(model => model.Hero.Name) to
#Html.TextBoxFor(**heroName** => **M**odel.Hero.Name). Semantically it
will be more correct & readable.
Do you have _Layout.cshtml in your project?
If so, why you are structuring the whole HTML in AddEdit.cshtml?
That way the HTML rendered to the browser becomes invalid and may be
some browser(s) don't (can't) parse it.
If you're using _Layout.cshtml, loose everything but the BODY content in AddEdit.cshtml
Do HEAD editions in _Layout.cshtml