ModelState.IsValid始终为true

时间:2017-07-07 15:56:35

标签: asp.net asp.net-mvc model-view-controller

在MVC中很常见,我有一个View,一个Model和一个Controller。

视图包含一个表单:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m => m.Id)
    <ul class="fieldlist">
        <li>
            @Html.LabelFor(m =>m.Email)
            @Html.TextBoxFor(m => m.Email)
            @Html.ValidationMessageFor(m => m.Email)
        </li>
        <li>
            <div class="row">
                <div class="col-md-6">
                    @Html.LabelFor(m => m.FirstName)
                    @Html.TextBoxFor(m => m.FirstName)
                    @Html.ValidationMessageFor(m => m.FirstName)
                </div>
                <div class="col-md-6">
                    @Html.LabelFor(m => m.LastName)
                    @Html.TextBoxFor(m => m.LastName)
                    @Html.ValidationMessageFor(m => m.LastName)
                </div>
            </div>
        </li>
        <li>
            @Html.LabelFor(m => m.PhoneNumber)
            @Html.TextBoxFor(m => m.PhoneNumber)
            @Html.ValidationMessageFor(m => m.PhoneNumber)
        </li>
        <li>
            <div Class="row">
                <div Class="col-md-2">
                    <input type="submit" value="Save" />
                </div>
            </div>
        </li>
    </ul>
}

该模型如下所示:

public class UserAdminUserViewModel
{
    [Display(Name = "User Database ID"), DataType(DataType.Text)]
    public string Id { get; set; }
    [Display(Name = "Full Name")]
    public string Name { get { return FirstName + " " + LastName; } }
    [Required()]
    [Display(Name = "First Name"), DataType(DataType.Text)]
    public string FirstName { get; set; }
    [Required()]
    [Display(Name = "Last Name"), DataType(DataType.Text)]
    public string LastName { get; set; }
    [Required()]
    [Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Display(Name = "Telephone Number"), DataType(DataType.Text)]
    public string PhoneNumber { get; set; }
}

接收更新的控制器:

[HttpPost,ValidateAntiForgeryToken]
public ActionResult User(UserAdminUserViewModel model)
{
    if (ModelState.IsValid)
    {
        // do something, apply the updates to the database, presumably
    }
    return View(model);
}

...但ModelState.IsValid 始终为true。控制器 接收输入的信息,但似乎没有进行验证。我试过了:

TryUpdateModel<UserAdminUserViewModel>(model);

UpdateModel<UserAdminUserViewModel>(model);

我不确定我看到这些是如何工作的,但它们是我遇到的第一个建议。没有骰子。无论“模型”中的数据如何,仍然有效。我也尝试过:

System.ComponentModel.DataAnnotations.Validator.ValidateObject(model, new System.ComponentModel.DataAnnotations.ValidationContext(model));

更有希望,但仍然无效。我也尝试了更详细的方法:

System.ComponentModel.DataAnnotations.ValidationContext valContext = new System.ComponentModel.DataAnnotations.ValidationContext(model, null, null);
List<System.ComponentModel.DataAnnotations.ValidationResult> valResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
System.ComponentModel.DataAnnotations.Validator.TryValidateObject(model, valContext, valResults, true);
foreach(System.ComponentModel.DataAnnotations.ValidationResult result in valResults)
{
    this.ModelState.AddModelError(result.MemberNames.FirstOrDefault() ?? string.Empty, result.ErrorMessage);
}

......这也行不通。 'valResults',它应该包含模型状态中的任何错误,从不填充;没有验证。

2 个答案:

答案 0 :(得分:1)

我会将其用于电子邮件验证:

@using using System.ComponentModel.DataAnnotations;

[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

请参阅此StackOverflow post

  

但是,EmailAddressAttribute在其上添加了服务器端验证   那。即如果您只使用,则没有服务器端验证   DataTypeAttribute!

答案 1 :(得分:0)

如果电子邮件地址不正确,请问以下解决方案:

[Email(ErrorMessage = "Invalid Email Address")]
[Required()]
[Display(Name = "Email Address"), DataType(DataType.EmailAddress)]
public string Email { get; set; }

DataType(DataType.EmailAddress)仅表示如何在客户端显示文本框,而Email属性则执行实际验证。