【问题标题】:ModelState.AddModelError and @Html.ActionLinkModelState.AddModelError 和 @Html.ActionLink
【发布时间】:2016-01-19 16:57:16
【问题描述】:

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

控制器

[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)
}

【问题讨论】:

  • 你的逻辑没有意义。如果需要地址,为什么它不是初始表单的一部分,它的属性用[Required] 属性修饰。如果不是,但您只是想提示用户添加它,那么添加 ModelStateError 是不合适的 - 只需将消息添加到视图模型或 ViewBag 属性并在视图中显示 t。

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


【解决方案1】:

您可以在视图中查看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)
}

【讨论】:

    猜你喜欢
    • 2014-02-14
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2014-09-30
    • 2015-07-27
    相关资源
    最近更新 更多