Asp.net mvc ModelState.addmodeleror和@Html.ActionLink

Asp.net mvc ModelState.addmodeleror和@Html.ActionLink,asp.net-mvc,forms,validation,actionlink,modelstate,Asp.net Mvc,Forms,Validation,Actionlink,Modelstate,是否可以使用ModelState.AddModelError验证@Html.ActionLink?在我的项目中,我试图引导用户向他们的个人资料中添加其他信息。当用户登录编辑他们的个人资料时,如果用户没有填写账单地址表单,我想向用户提示一个验证错误 控制器 [HttpPost] public ActionResult Edit(UserProfile model) { if (model.Address == null) {

是否可以使用
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);
模型

[显示(Name=“地址”)]
[必需(ErrorMessage=“请输入帐单地址”)]
公共可空地址ID{get;set;}
看法

if(Model.Address==null)
{

@ActionLink(“添加账单地址”、“创建”、“地址”、新建{returnUrl=“UserProfile/Edit”,userId=Model.userId},null) @Html.ValidationMessageFor(m=>m.Address) } 其他的 { @DisplayFor(m=>m.Address.Line1)
@如果(Model.Address.Line2!=null) { @DisplayFor(m=>m.Address.Line2)
} @Html.DisplayFor(m=>m.Address.City),@Html.DisplayFor(m=>m.Address.State.缩写)@Html.DisplayFor(m=>m.Address.PostalCode) @ActionLink(“编辑地址”、“编辑”、“地址”,新的{id=Model.AddressId,returnUrl=“UserProfile/Edit”,userId=Model.userId},null) }
您可以在视图中检查
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)
}

你的逻辑没有道理。如果地址是必需的,为什么它不是初始表单的一部分,其属性用
[required]
属性修饰。如果不是,但您只是想提示用户添加它,则添加
modelstatererror
是不合适的-只需向视图模型或
ViewBag
属性添加消息,并在视图中显示t即可。
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)
}
@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)
}