【问题标题】:Posting Form to Partial View via AJAX通过 AJAX 将表单发布到部分视图
【发布时间】:2018-06-30 15:51:44
【问题描述】:

我正在尝试将数据从部分视图表单 (viewbag) 发布到主控制器上的操作方法。我正在使用 Jquery:

$.ajax({
    url: '@Url.Action("displaypreviewformactionmethod", "MyMainController")',
    type: 'post',
    dataType: 'json',
    data: $('form#realform').serialize(),
    success: function (data) {
        $('#DivTagWhereMyPartialViewIs').html(data);
        $('#DivTagWhereMyPartialViewIs').show();
    }

我的表单部分视图如下所示:

<div id="step-3" class="">
    @using (Html.BeginForm("displaypreviewformactionmethod", "MyMainController"))
    {
        foreach (var frm in Model)
        {
            <tr>
                <td>
                    @Html.LabelFor(model => model.FirstOrDefault().ELabel, frm.SomeText)
                </td>
                <td>
                    @Html.TextBox(frm.FieldName)<br />
                </td>
            </tr>
        }
        <input type="submit" name="Submit" value="Submit" />
    }
</div>

主控制器中的action方法是:

public ActionResult displaypreviewformactionmethod(FormCollection form)
{
    if (form.Count > 0)
    {
        ViewBag.FormItems = form;
    }
    return PartialView("MyPartialView", form);
}

该操作被调用,但它没有将 formcollection 中的任何内容传递给局部视图 - 这使我相信我没有正确识别局部视图中的表单。我尝试在局部视图中添加&lt;form id="realform"&gt;,但这没有用。有没有其他方法可以在 Jquery 中识别表单?

非常感谢任何方向。

【问题讨论】:

  • 您的表单没有id="realform" - 但您可以使用@using (Html.BeginForm("displaypreviewformactionmethod", "MyMainController", FormMethod.Post, new { id = "realform" })) 添加它。是什么触发了 ajax 调用?而且您的 foreach 循环无论如何都不会正确绑定 - 请参阅 this answer
  • 你的局部视图不是强类型的有什么原因吗?将模型发布到控制器会更容易..
  • 局部视图有模型...... OP只放置了局部视图的一部分......它是不应该有formcollection的控制器
  • @StephenMuecke - 你的答案适用于我想要做的事情:(Html.BeginForm("displaypreviewformactionmethod", "MyMainController", FormMethod.Post, new { id = "realform" })) 我会将其标记为答案,但不能因为它是回复。

标签: jquery asp.net-mvc forms partial-views formcollection


【解决方案1】:

@AMorrisey 我了解到您希望通过 ajax 提交表单。但是我在您的代码中看到了很多建议..

1. Razor 可以处理 ajax 表单提交.. 不需要编写外部 ajax 使用

@using (Ajax.BeginForm("displaypreviewformactionmethod", "MyMainController",

插入

@using (Html.BeginForm("displaypreviewformactionmethod", "MyMainController"))

这是了解Ajax.BeginForm vs Html.BeginForm之间区别的好文章

2.其次是你的

$.ajax({
    type: 'post',..

不会因为&lt;input type="submit" name="Submit" value="Submit" /&gt;而产生任何影响

点击提交按钮时,它会直接点击控制器/动作。所以$ajax部分没用

3.动作中应该有适当的模型绑定

public ActionResult displaypreviewformactionmethod(FormCollection form)

should have been

public ActionResult displaypreviewformactionmethod(SomeModel model)

【讨论】:

  • 显然 $.ajax() 正在工作,因为 OP 已经声明了它的方法(并且建议使用 Ajax.BeginForm() 而不是 $.ajax() 是糟糕的建议)
  • 感谢 Raja - 我无法使用模型,因为表单内容(字段和字段值)是动态生成的,因此使用 ViewBag。
猜你喜欢
  • 2018-02-10
  • 2018-09-26
  • 2013-04-04
  • 2015-03-17
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多