Reputation: 27
I have a Model class in which i did something like that:
[Required]
public string Name {get; set;}
[Required]
public string Username {get; set;}
When i create a view based on this class and clicks the submit button without any data it does not show the validation message for that required attribute. Why?
Upvotes: 0
Views: 1037
Reputation: 1178
Firstly show us your view and also use validation message html helper as shown below.
@Html.ValidationMessageFor(m=>m.Name)
use this after you html helper for which you want to access the message.
Update
You can also custom edit your model just like
[Required(ErrorMessage="Enter The Name")]
public string Name {get; set;}
[Required(ErrorMessage="Enter The Username")]
public string Username {get; set;}
Upvotes: 1
Reputation: 5989
you have to do certain things to make it work as per your expectations.
First you have to make sure you have provision to render error messages related with specific field like following in your .cshtml
page
@Html.EnableClientSideValiation()
@Html.EnableUnObstructiveJavascript()
// your other form elements
@Html.TextBoxFor(x=> x.Name)
@Html.ValidationMessageFor((x=> x.Name) // this will render validations if any
to make trigger validations on client side it self you have to enable client side validations and include required JS files
You should also make proper checks on server side, in your action method in controller you should have something like...
[HttpPost]
public ActionResult Save(Your_Type model)
{
if(ModelState.IsValid()) // it will ensure all your annotations are passed
{
// save to server
// redirect to appropriate page
}
else
{
return View(model); // it will render same form again with already entered values and errors
}
}
Upvotes: 2