Reputation: 1195
Edit.aspx:
<th>Calendar<input id="datepicker" name="datepicker" type="text" class="input-box"/></th>
Controller action:
// POST: /Studenti/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int[] rb, int id, string datepicker)
{
List<nastava_prisustvo> nastava = new List<nastava_prisustvo>();
if (String.IsNullOrEmpty(datepicker))
ModelState.AddModelError("datepicker", "First name is required");
try
{
if (ModelState.IsValid)
{
string poruka = "";
for (int i = 1; i <= rb.Length; i++)
{
string name = "chk" + i;
string selID = Request.Form[name];
if (selID == "on")
{
nastava.Add(new nastava_prisustvo
{
br_indexa = int.Parse(Request.Form["id_stud" + i]),
id_predmet = id,
datum = System.DateTime.Parse(Request.Form["datepicker"])
});
}
}
return View("show", nastava);
}
}
catch(Exception ex){
ModelState.AddModelError("*", "An unexpected error occurred.");
}
return View("show", nastava);
}
}
How to validate datepicker fiel? How stop posting data if date is not selected and show appropriate message. I use ASP>NET MVC 1 and read this http://www.superexpert.com/Blog/archive/2008/09/09/asp-net-mvc-tip-42-use-the-validation-application-block.aspx but did not solve my problem
Upvotes: 1
Views: 506
Reputation: 878
I would stick to server side validation. Try this:
DateTime datePosted;
if (!DateTime.TryParse(Request.Form["datepicker"], out datePosted))
{
this.ModelState.AddModelError("datepicker", "Invalid Date!");
}
if (this.ModelState.IsValid)
{
return View("show", nastava);
}
else
{
// return your GET edit action here
return Edit(5);
}
Your Edit view will automatically be passed any validation errors and you can display them with a validation summary.
<%= Html.ValidationSummary() %>
Upvotes: 1
Reputation: 6562
since you have validate on the client with your own Javascript, try the jQuery UI data picker: http://jqueryui.com/demos/datepicker/
Then, most simply, on the server side, you can take the string value "datepicker" Convert it in a try/catch.
var dtDatePicker = new DateTime();
try
{
dtDatePicker = Convert.ToDateTime(datepicker);
// worked, carry on
}
catch
{
// didn't work, invalid date.
}
Upvotes: 0
Reputation: 6499
ASP.NET MVC does not use the same sort of controls you're used to using in ASP.NET. Basically you have to do most things manually in JavaScript code, whereas in ASP.NET it generates that code automatically.
I'd use JQuery or something to validate the data in the control on the button click.
Upvotes: 1
Reputation: 5018
If you want to validate the date before posting back you're going to have to use client side validation. xVal is a popular plugin for this.
For server side validation you're going to want to look at model binding and model validation.
Upvotes: 1