【问题标题】:MVC 5 partial view async postbackMVC 5 部分视图异步回发
【发布时间】:2015-08-04 19:42:01
【问题描述】:

我有一个主从编辑表单,我正在尝试关注这个帖子:Using Ajax... 以获取回发的部分视图。

我的编辑表单有一个包含子项目列表的部分视图,以及另一个用于添加新项目的部分创建视图。如果可能的话,我希望部分创建视图在不刷新整个页面的情况下发回并更新列表。

这是我目前所拥有的:

MyController.cs -

public ActionResult Edit(int? id)
{
    //...
    ViewBag.CustomFormId = id;
    using (var _db = new MkpContext())
    {
        //...
        return View(profileEdit);
    }
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomForm editForm)
{
    //...
    if (!ModelState.IsValid) return View(editForm);
    using (var _db = new MkpContext())
    {
        var form = _db.CustomForms.Find(editForm.CustomFormId);
        //...
        _db.Entry(form).State = EntityState.Modified;
        _db.SaveChanges(User.ProfileId);
        return RedirectToAction("Index");
    }
}

public ActionResult _CustomFieldList(int id)
{
    ViewBag.CustomFormId = id;
    using (var _db = new MkpContext())
    {
        var formCustomFields = (from cf in _db.CustomFields
                                where cf.CustomFormId == id
                                select cf);
        return PartialView(formCustomFields.ToList());
    }
}

// Nested in _CustomFieldList
public ActionResult _CustomFieldCreate(int id)
{
    var newField = new CustomField
    {
        CustomFormId = id
    };
    return PartialView(newField);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _CustomFieldCreate(CustomField addField)
{
    ViewBag.CustomFormId = addField.CustomFormId;
    if (ModelState.IsValid)
    {
        using (var _db = new MkpContext())
        {
            _db.CustomFields.Add(addField);
            _db.SaveChanges();
        }

        var newField = new CustomField
        {
            CustomFormId = addField.CustomFormId
        };
        return PartialView(newField); // Probably need to change this somehow
    }
    return PartialView(addField);
}

还有意见:

Edit.cshtml -

@model PublicationSystem.Model.CustomForm
@{
    ViewBag.Title = "Edit Custom Form";
    Layout = "~/Views/Shared/_LayoutSmBanner.cshtml";
}
    <div class="form-horizontal">
        <div class="row">
        @using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @* Fields for this form *@
        }
        <div id="CustomFields" class="col-md-6">
            @Html.Action("_CustomFieldCreate", new { id = ViewBag.CustomFormId })
        </div>
    </div>
</div>

<script>
$(function () {
    $("#createFieldForm").on("submit", function (e) {
        e.preventDefault(); //This prevent the regular form submit
        $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $("#CustomFields").html(result);
                }
            });
        return false;
    });
});
</script>

_CustomFieldCreate.cshtml -

@model PublicationSystem.Model.CustomField
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    <div id="result"></div>
    <div class="form-horizontal">
        <h4>CustomField</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model =>model.CustomFormId)

    <div class="row">
        @* Fields for the form *@
    </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div id="customFieldList">
    @Html.Action("_CustomFieldList", new { id = ViewBag.CustomFormId })
</div>

_CustomFieldList.cshtml

@model System.Collections.Generic.IEnumerable<PublicationSystem.Model.CustomField>
<table class="table">
    @* List table code *@
</table>

编辑:我重写了页面,使列表成为创建局部视图的一部分。现在发生的情况是,如果您为 _CustomFieldCreate 输入数据并第一次按下提交,它只会刷新该视图(包括嵌套列表视图)。但是第二次,它重定向到视图,可能是因为第一次刷新没有将 javascript 重新绑定到提交按钮。此外,创建视图不会清除字段,而是保留最初输入的数据。

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    您需要在局部视图中创建一个表单,其提交操作绑定到一个 javascript 函数,该函数会发布到您的控制器。

    例如,如果您的表单 ID 是 MyForm:

     $('#MyForm').on('submit', function (e) {
        e.preventDefault(); //This prevent the regular form submit
        $.ajax({
            url: $(this).action, // This will submit the post to whatever action your form goes to
            type: "POST", // This tells it that it is a post
            data: $(this).serialize(), // This sends the data in the form to the controller
            success: function (data) {
                // do some javascript on success
            },
            error: function (xhr, ajaxOptions, thrownError) {
                // do some javascript on error
            }
        });
    });
    

    这个 javascript 会覆盖默认的表单提交,并向您的控制器发送 ajax 帖子,然后返回成功或错误,您可以在其中执行任何操作。

    这里是一些 jquery ajax 文档:

    http://api.jquery.com/jquery.ajax/

    【讨论】:

      【解决方案2】:

      您应该考虑使用 AJAX。这应该完成我认为你所描述的。您需要创建一个 javascript 函数来处理表单上的提交事件,然后使用 AJAX 将表单数据发布到您的 MVC 应用程序中的某个创建操作。如果您使用的是 jQuery,那么该库会变得非常简单。 http://api.jquery.com/jquery.ajax/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-30
        • 2012-04-28
        相关资源
        最近更新 更多