.Net MVC ModelState.IsValid始终返回true

时间:2015-12-18 14:06:00

标签: validation model-view-controller modelstate

ModelState.IsValid始终返回true。

代码:

user.cs

public class User
{

    public int UserID { get; set; }

    public string Username { get; set; }
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}

HomeController.cs

public ActionResult SaveUser(User user)
    {
        if (ModelState.IsValid)
        {
            //create DBContext object
            using (var dbCtx = new UsersDbEntities())
            {
                dbCtx.Entry(user).State = EntityState.Modified;

                dbCtx.SaveChanges();
            }
            return View("ShowUser", user);
        }
        return View("EditUser", user);

    }

Register.cshtml

     @model TrainingWebsite.Models.User

<div id="myForm">
    @using (Html.BeginForm("RegisterUser", "Home", FormMethod.Post))
    {
    if (@ViewBag.Message != null)
    {
        <div style="border: 1px solid red">
            @ViewBag.Message
        </div>
    }
    <table>
        <tr>
            <td>@Html.LabelFor(a => a.Username)</td>
            <td>@Html.TextBoxFor(a => a.Username, new { id = "id_username" })</td>
            <td>@Html.ValidationMessageFor(a => a.Username)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(a => a.FirstName)</td>
            <td>@Html.TextBoxFor(a => a.FirstName, new { id = "id_firstName" })</td>
            <td>@Html.ValidationMessageFor(a => a.FirstName)</td>
        </tr>
        <tr>
            <td>@Html.LabelFor(a => a.LastName)</td>
            <td>@Html.TextBoxFor(a => a.LastName, new { id = "id_lastName" })</td>
            <td>@Html.ValidationMessageFor(a => a.LastName)</td>
        </tr>
 </table>

Register form

即使“姓名”字段为空但是必填字段,ModelState.IsValid也为true ModelState.IsValid = true

任何帮助将不胜感激。提前致谢

大卫

0 个答案:

没有答案