在MVC视图中使用jQuery添加Html.BeginForm

时间:2017-10-20 13:11:05

标签: jquery html ajax asp.net-mvc

我有一些信息框,所有信息都是用Ajax加载的,在我的控制器中调用一个函数,然后构建HTML。

我需要这些信息框的一些编辑功能,它们只需用表单替换静态文本。我知道如何在常规HTML中执行此操作但我想使用Html.BeginForm以便我可以在控制器中处理它。

这就是我想在表单中加载的方式(它与加载静态信息框的代码几乎相同)

$.ajax({
    url: '@Url.Action("GetCustomerInfoById/")' + id,
    type: 'post',
    traditional: true,
    dataType: 'json',
    success: function (result) {
        $.each(result.CustomerInfo, function (index, customerInfo) {
            $('#infoBox' + customerInfo.ID).html(/* html form goes here */);
        });
    }
})

这就是我想要构建表单的方式

@using (Html.BeginForm("Index", "Customer", FormMethod.Post, new { @class = "form-horizontal" }))
{
    @model CustomerInfo

    <div class="form-group">
        @Html.TextAreaFor(m => m.InfoText, new { @class = "form-control col-12-md", @style = "max-width: none", @rows = "5" })
    </div>
    <div class="form-group">
        @Html.DropDownListFor(m => m.InfoTypeId, new SelectList(InfoTypeList, "Value", "Text"), new { @class = "form-control", @style = "max-width: none" })
    </div>
    <input type="submit" value="Gem" class="btn btn-primary" />
}

1 个答案:

答案 0 :(得分:0)

您可以通过使用customerInfo.ID作为参数创建一个新的Controller ActionMethod来实现此目的,这会将您的表单呈现为部分视图。

表单需要为ID提供一个隐藏字段,因此如果发布表单帖子可以彼此区分。

使用循环内的其他$.ajax()调用调用新的ActionMethod,每个调用都有一个成功函数,将结果传递给.html()语句。