I have an asp.net mvc4 application in which i'd like to use the fields validation :
My Model class :
namespace sample_mvc4.Models
{
public class User
{
[Required(ErrorMessage="Enter le nom")]
public string Name;
[Required(ErrorMessage = "Enter l'émail")]
public string Email;
[Required(ErrorMessage = "pas de mdp!!!!")]
public string Password;
}
}
The Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Register");
}
public ActionResult Register(User u)
{
if (ModelState.IsValid)
{
string s = u.Name;
return View("Index");
}
else
{
return View();
}
}
}
And finally the view Register.cshtml
@model sample_mvc4.Models.User
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link type="text/css" href="~/Content/Site.css" />
<title>Register</title>
</head>
<body>
@using(Html.BeginForm("Register","Home")){
@Html.ValidationSummary()
<p> Name: @Html.TextBoxFor(x => x.Name)</p>
<p> Email : @Html.TextBoxFor(x => x.Email)</p>
<p> Password : @Html.TextBoxFor( x=>x.Password)</p>
<input type="submit" value="Register" />
}
</body>
</html>
My problem are :
- When i let a field or more empty , the error message isn't appear, why?
- In the action
Registerthe User object's fields are always all null - When i submitted the form , inside the action
Register, theModelState.IsValidtakes always true
What are the reasons of these results? How can i fix my code?