dimanche 19 avril 2015

ValidationMessage asp.net mvc

I have a question about ModelState.AddModelError method and about the ValidationMessage method.


I am new to ASP.NET MVC and I am a little confused.


I wrote this code:



public ActionResult update(FormCollection collection)
{
int oos = 0;

try
{
oos = int.Parse(collection[0]);
}
catch
{
}

data d = new data();

TryUpdateModel(d , collection.ToValueProvider());

if (ModelState.IsValid)
{
return View("index",d);
}
else
{
ModelState.AddModelError("Date", "Wronge Date");
d.Id = 50;
return View("index",d);
}
}


and this code in the view side



@{

ViewBag.Title = "index";
}

<h2>index</h2>
@TempData["Hi"]


@Html.ValidationMessage("fullname")

@using (Html.BeginForm())
{
@Html.AntiForgeryToken() @Html.TextBox("id", 70)
@Html.TextBox("Date", "3/2/1991 12:00:00 ص")
@Html.ValidationMessage("Date","Please insert the correct Date Format")

<input type="submit">
}


My questions are, why the message Please insert the correct Date Format appears directly when I rune the index while still I did not submit the index, why when I submit the form with error in the date format the same message appear but not the message that I set to the Date Key in the update method which is Wronge Date.


maybe still I do not understand those two methods so I hope to find somebody to explain them to me.


explnation with example or reference would be appreciated


Aucun commentaire:

Enregistrer un commentaire