ModelState.AddModelError和@ Html.ActionLink

时间:2016-01-19 16:57:17

标签: asp.net-mvc forms validation actionlink modelstate

是否可以使用@Html.ActionLink验证ModelState.AddModelError?在我的项目中,我尝试引导用户在其个人资料中添加其他信息。当用户登录以编辑他们的个人资料时,如果用户尚未填写用于记帐地址的表单,我想提示用户出现验证错误。

控制器

[HttpPost]
    public ActionResult Edit(UserProfile model)
    {
        if (model.Address == null)
        {
            ModelState.AddModelError("", "please enter in a address");
        }
        model.Address = db.Addresses.SingleOrDefault(a => a.AddressId == model.AddressId);

模型

[Display(Name = "Address")]
[Required(ErrorMessage = "please enter in a billing address")]
public Nullable<int> AddressId { get; set; }

查看

if (Model.Address == null)
{
    <br/>

    @Html.ActionLink("Add a billing address", "Create", "Address", new { returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
    @Html.ValidationMessageFor(m => m.Address)
}
else
{
    <div class="editor-field">
        @Html.DisplayFor(m => m.Address.Line1)<br />
        @if (Model.Address.Line2 != null)
        {
            @Html.DisplayFor(m => m.Address.Line2)<br />
        }
        @Html.DisplayFor(m => m.Address.City), @Html.DisplayFor(m => m.Address.State.Abbreviation) @Html.DisplayFor(m => m.Address.PostalCode)
    </div>

    @Html.ActionLink("Edit address", "Edit", "Address", new { id = Model.AddressId, returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
}

1 个答案:

答案 0 :(得分:0)

您可以查看视图中的ModelState

@model ModelWithAddress

@{
    var address = ViewContext.ViewData.ModelState["Address"];
}

@if (address != null && address.Errors.Count() > 0)
{
    @Html.ActionLink("Add a billing address", "Create", "Address",
        new { returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
}