如何使用 AJAX 呈现部分表单元素 [英] How do I render a partial form element using AJAX

查看:28
本文介绍了如何使用 AJAX 呈现部分表单元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,可以组合一个更大表格的部分.例如:

I have a form that assembles sections of a larger form. For example:

Html.RenderPartial("Partials/MealPreference", Model);

我想动态地向表单添加部分.鉴于我的部分视图的性质,我也必须传递模型.在这方面,我很失败.

I would like to dynamically add sections to the form. Given the nature of my partial views, I must pass the model along as well. In that, I am failing miserably.

我的包含页面上的标记:

The markup on my containing page:

<div id="additionalPreference"></div>

<input type="button" value="Add Additional Preference" id="addPreference" />


<script>
    $(document).ready(function () {
        $('#addPreference').click(function () {

            $.ajax({
                type: "POST",
                url: '@Html("AddPreference", "Main")',
            success: function (html) {
                $(html).appendTo('#additionalPreference');
                console.log(html);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Error");
            },
            complete: function () {
                console.log("End");
            }
        });
    });
});
</script>

我的控制器操作:

[HttpPost]
public ActionResult AddPreference(FormViewModel model)
{
    if (ModelState.IsValid)
    {
        return PartialView("Partials/AdditionalPreference", model);
    }
    else
    {
        return PartialView("Partials/LoadFailed");
    }
}

该模型永远无效.如何将模型从包含页面传递给控制器​​操作?这似乎是一件很简单的事情(它肯定会在 Web 表单中),但我已经为此窒息了 3 个小时.

The model is never valid. How do I pass the model form the containing page to the controller action? This would seem to be something simple to do (it certianly would be in Web Forms) but I have been choking on this for 3 hours.

推荐答案

对于 ajax 调用,您必须构建模型:

For an ajax call you have to build the model:

$.ajax({
    type: "POST",
    url: '@Url.Action("AddPreference", "Main")',
    data: {
        Field1: 'field1',
        Field2: 'field2'
    },
    success: function (html) {
         $(html).appendTo('#additionalPreference');
         console.log(html);
    },
    error: function (xhr, ajaxOptions, thrownError) {
         alert("Error");
    },
    complete: function () {
         console.log("End");
});

确保 ajax 调用的数据部分中的名称与模型中的名称完全匹配,并且它应该显示在填充的控制器中.

Make sure that the names in the data section of the ajax call match exactly the names in your model and it should show up in your controller populated.

更新:

自从写这个答案以来,我学到了更多关于通过 ajax 将信息发送回控制器的知识.正如 Rick Dailey 所评论的,您可以通过以下方式将提交到表单的模型发送回控制器:

Since writing this answer I have learned more about sending information back to the controller via ajax. As commented by Rick Dailey you can send the model submitted to the form back to the controller via:

@Html.Raw(Json.Encode(Model))

我发现了序列化,我们使用:

I have found out about serialize and we use:

$('form').serialize() 

将表单上的字段发送回控制器.一种将所有信息发回的快速、简单的方法,类似于回发,而无需手动构建模型.

To send the fields on the form back to the controller. A quick, easy way to send all information back similar to a post back without having to manually build the model.

这篇关于如何使用 AJAX 呈现部分表单元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆