【问题标题】:How to pass an object with a MVC ajax form to controller如何将具有 MVC ajax 表单的对象传递给控制器
【发布时间】:2016-11-23 18:57:12
【问题描述】:

您好,我有以下 Razor 视图:

@model AgonConFF.ViewModels.ClaimModel

@using (Ajax.BeginForm("DataCaptureNew", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "result", OnBegin = "onBegin()", OnComplete = "onComplate()" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.Origin.SourceName, new { htmlAttributes = new { @class = "form-control CapInput", placeholder = "Source Name" } })
    @Html.ValidationMessageFor(model => model.Origin.SourceName, "", new { @class = "text-danger" })
    @*Source Name*@

    @Html.EditorFor(model => model.Origin.MailFax, new { htmlAttributes = new { @class = "form-control CapInput", placeholder = "Mail Address / Fax Nr" } })
    @Html.ValidationMessageFor(model => model.Origin.MailFax, "", new { @class = "text-danger" })
    @*Mail Address / Fax Nr*@

    <input type="submit" value="Capture" class="btn btn-default" />
}

我的 JS 看起来像这样:

function onBegin() {
    $('#loading').show();
}

function onComplate() {
    $('#loading').hide();
}

我的控制器看起来像这样:

//Action method that handles the testCreate form submission
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult DataCaptureNew(ClaimModel origin)
{
    if (ModelState.IsValid)
    {
       db.Origins.Add(origin.Origin);
       origin.Origin.OriginID = 1;
       db.SaveChanges();
       return PartialView("testPartial", origin);
    }

    return PartialView("testPartial", origin);
}

当我提交表单并使用断点检查控制器内部时,我看到ClaimModel origin 的相关对象为空并给我一个错误。当我只使用Html.BeginForm 时,这篇文章非常有效。在这种情况下,Origin 对象可以很好地通过。如何使用Ajax.BeginForm 传递此对象?

【问题讨论】:

    标签: ajaxform asp.net-mvc-5 ajax.beginform


    【解决方案1】:

    我有一个非常相似的要求,我将分享在这种情况下对我有用的方法。我基本上用Form data serialization。我也使用了Html.BeginForm,所以我正在相应地修改上面的代码。

    第 1 步 为您的表单分配一个 ID。我用过"claim_form"。添加一个按钮并为其提供一个ID。我在下面使用id="click"

    @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "claim_form" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    
        @Html.EditorFor(model => model.Origin.SourceName, new { htmlAttributes = new { @class = "form-control CapInput", placeholder = "Source Name" } })
        @Html.ValidationMessageFor(model => model.Origin.SourceName, "", new { @class = "text-danger" })
    
    
        @Html.EditorFor(model => model.Origin.MailFax, new { htmlAttributes = new { @class = "form-control CapInput", placeholder = "Mail Address / Fax Nr" } })
        @Html.ValidationMessageFor(model => model.Origin.MailFax, "", new { @class = "text-danger" })
    
    
        <input type="submit" value="Capture" class="btn btn-default" />
        <input type="button" id="click" class="btn btn-default" />
    }
    

    第 2 步: Ajax 调用

    $('#click').click(function(e) {
    
    
                   //Say your controller is ClaimController
                    var url = '@Url.Action("DataCaptureNew","ClaimController")';
    
                    $.ajax({
                        type: 'POST',
                        url: url,
                        data:$("#claim_form").serialize(),
    
                       //no need to give the content -type here
                        success: function(data) {
    
                        },
                        error: function(xhr, ajaxOptions, thrownError) {
    
                        }
    
                    });
    
                });
    

    第 3 步:修改模型绑定的控制器方法

    [HttpPost]
        public JsonResult DataCaptureNew(FormCollection col)
        {
    
            //Model Binding usimg TryUpdateModel
            var testClaim = new ClaimModel();
            var tstVal = TryUpdateModel<ClaimModel>(testClaim ,col);
            //namespace for ClaimModel here say it is AgonConFF.ViewModels.ClaimModel
            var claim1 = Type.GetType("AgonConFF.ViewModels.ClaimModel");
            //While debugging you will b eable to see how claim2 gets updated with the fields from formCollection
            var claim2= Activator.CreateInstance(claim1);
    
            var binder = Binders.GetBinder(claim1);
    
            var bindingContext = new ModelBindingContext()
            {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => claim2, claim1),
                    ModelState = ModelState,
                    ValueProvider = col
            };
    
            binder.BindModel(ControllerContext, bindingContext);
            if (ModelState.IsValid)
            {
                    System.Diagnostics.Debug.WriteLine("Model is valid here");
            }
    
    
           return Json(claim2);
    
        }
    

    注意:claim2 应该有所需的模型。 我正在从该方法返回一个 Json 结果。您可以检索 Json 结果并在部分视图中呈现它。

    【讨论】:

      猜你喜欢
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多