1

当我尝试直接在浏览器中加载部分视图并提交它时显示错误消息,但如果相同的部分视图在另一个视图中,它不会显示该模型错误验证。在我使用 Ajax.Beginform 方法的视图中加载部分视图。

在浏览器中加载局部视图时 在此处输入图像描述

包含在另一个视图中时 在此处输入图像描述

我的部分观点

@model FPW.FPWClientModels.SiteClientModel
@if (this.ViewContext.FormContext == null)
{
    this.ViewContext.FormContext = new FormContext();
}

    @using (Ajax.BeginForm("CreateSite", "Site", null, new AjaxOptions
    {
        HttpMethod = "POST",
        AllowCache = false,
        ////LoadingElementId = "AjaxOverlay",
        //OnSuccess = "SiteOnSaveSuccess",
        //OnFailure = "SiteOnSaveFailure",
    }, new { @id = "SiteCreateForm" }))
    {
        <div class="modal-body">
            @Html.AntiForgeryToken()            

            <div class="form-group">
                @Html.LabelFor(model => model.SiteName, htmlAttributes: new { @class = "control-label" })
                <div class="col-md-12">
                    @Html.EditorFor(model => model.SiteName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.SiteName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.SiteAddress, htmlAttributes: new { @class = "control-label" })
                <div class="col-md-12">
                    @Html.EditorFor(model => model.SiteAddress, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.SiteAddress, "", new { @class = "text-danger" })
                </div>
            </div>


        <div class="modal-footer">
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>

    }

    <script>
        function SiteOnSaveSuccess(resp) {            
        }

        function SiteOnSaveFailure(resp) {            
        }
    </script>

我的控制器

public ActionResult CreateSite()
    {
        SiteClientModel oSiteClientModel = new SiteClientModel();
        return PartialView(oSiteClientModel);
    }

    //Create Site
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateSite(SiteClientModel oSiteClientModel)
    {
        if (ModelState.IsValid)
        {
            var saveSiteDetails = oSiteApiController.CreateSiteDetails(oSiteClientModel);
            return PartialView(saveSiteDetails);
        }
        else
        {
            oSiteClientModel.ReturnValue = new ReturnValue { IsSuccess = false, ReturnType = ReturnType.Error, Message = "Form Not Valid" };
        }
        return PartialView("CreateSite",oSiteClientModel);
    }
4

1 回答 1

1

发现错误。在 ajax 选项中未使用更新目标 ID。使用 UpdateTargetId 并将其指向表单 id 后,它按预期工作正常

于 2020-01-21T05:24:18.753 回答