如何将具有MVC ajax形式的对象传递给控制器

时间:2016-07-20 13:39:31

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

您好我有以下剃刀视图:

libraryname_dimen"

我的JS看起来像这样:

@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" />
}

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

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传递此对象?

1 个答案:

答案 0 :(得分:0)

我有一个非常相似的要求,我会分享在这种情况下对我有用的东西。我基本上使用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 Call

$('#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结果并在局部视图中呈现它。