【问题标题】:Pass the result of AJAX callback to Partial View using JQuery使用 JQuery 将 AJAX 回调的结果传递给局部视图
【发布时间】:2014-02-17 09:54:28
【问题描述】:

我正在使用 ASP.NET MVC 4。单击按钮时,我想调用控制器方法的 ajax 回调并将所需的数据作为 Json 数据返回。我可以使用以下代码来做到这一点:

<script>
$(document).ready(function () {
    var ajax_url = '@Url.Action("GetNewItems")';
    $("#submit").click(function () {
        $.ajax({
            url: ajax_url,
            type: "POST",
            datatype: "json",
            success: function (data) {
                debugger
            }
        });
    });
});

[HttpPost]
    public JsonResult GetNewItems()
    {
        List<Item> items = new List<Item>();

        items.Add(new Item() { Id = 3, Name = "c" });
        items.Add(new Item() { Id = 4, Name = "d" });

        return Json(items);
    }

在success函数中,Item集合被正确返回。在这个函数中,我想调用 Html.Partial 并将结果作为 Partial 视图的模型传递。这可能吗?

我在其他线程中搜索过,但大多数都建议从 Controller 方法返回 Partial View 并使用 html(data) 来呈现它。我宁愿不从 Controller 返回 Partial 视图,因为大小会有很大差异,而不是只返回数据并在客户端手动呈现。

那么,是否可以在成功函数中将结果传递给部分视图,或者我必须手动渲染其中的元素?

感谢任何帮助。谢谢!

【问题讨论】:

    标签: javascript jquery asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    那么有什么问题吗?去做吧

        [HttpPost]
        public ActionResult GetNewItems()
        {
            List<Item> items = new List<Item>();
    
            items.Add(new Item() { Id = 3, Name = "c" });
            items.Add(new Item() { Id = 4, Name = "d" });
    
            return View("MypartialView",items);
        }
    
    $(document).ready(function () {
        var ajax_url = '@Url.Action("GetNewItems")';
        $("#submit").click(function () {
            $.ajax({
                url: ajax_url,
                type: "POST",
                success: function (data) {
                    $("#div").html(data);
                }
            });
        });
    });
    

    【讨论】:

    • 正如我之前提到的,我只想返回数据(不是 HTML)以减少回调中发送的大小。
    【解决方案2】:

    那么,是否可以将结果成功传递给部分视图 函数,还是我必须手动渲染那里的元素?

    你可以通过几种方式解决这个问题 -

    JQuery 模板解决方案

    首先参考以下 JQuery 库 -

    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>
    

    然后创建您要填写详细信息的模板 -

    <script id="personsTmpl" type="text/x-jquery-tmpl">
        <tr>
            <th>${Name}</th>
        </tr>
    </script>
    

    下一步在 html 中定义表格 -

    <table id="tableAttendees">
        <thead>
            <tr>
                <th>Name</th>
            </tr>
        </thead>
        <tr></tr>
    </table>
    

    在页面上有一个按钮 -

    <input type="button" value="Click" onclick="submitForm()" />
    

    最后处理提交按钮的JQuery Click事件——

    <script>
        function submitForm() {
            jQuery.ajax({
                type: "POST",
                url: "@Url.Action("Submit")",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ name: "Rami" }),
                success: function (data) {
                    $("#personsTmpl").tmpl(data).appendTo("#tableAttendees");
                },
                failure: function (errMsg) {
                    alert(errMsg);
                }
            });
        }
    </script>
    

    当按钮被点击时,Submit Action 会被点击 -

        public ActionResult Submit(string name)
        {
            return Json(new Person() { Name = name + " Its Me" });
        }
    

    这将返回人对象 -

    public class Person
    {
        public string Name { get; set; }
    }
    

    现在,当您运行应用程序并单击按钮时,您将看到值附加到下表中 -

    您也可以使用如下所示的 AJAX 表单。

    AJAXFORM 解决方案

    假设你有如下索引 -

    @model MVC.Controllers.Person
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    
    @using (Ajax.BeginForm("Submit", new AjaxOptions { UpdateTargetId = "productList" }))
    {
        <div>
            @Html.LabelFor(model => model.Name)
            @Html.EditorFor(model => model.Name)
        </div>
        <div>
            <input type="submit" value="Add Product" />
        </div>
    }
    
    <div id='productList'>
        @{ Html.RenderPartial("itsme", Model); }
    </div>
    

    哪个会点击提交操作,然后我们会得到一个局部视图 -

        public ActionResult Submit(Person p)
        {
            p.Name = p.Name + " Its me";
            return PartialView("itsme", p);
        }
    

    局部视图很简单,显示名称 -

    @model MVC.Controllers.Person
    
    @if (Model != null)
    {
        @Html.LabelFor(p => p.Name, Model.Name)
    }
    

    终于输出了——

    【讨论】:

      【解决方案3】:

      如果您不想返回部分视图,则必须使用客户端代码来完成此操作。有几种选择。您可以查看 jTempaltes 和 jQuery 模板作为选项。但是,如果您不会多次调用此 Ajax,我建议您返回 Partial View。

      【讨论】:

        猜你喜欢
        • 2017-01-21
        • 1970-01-01
        • 1970-01-01
        • 2013-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-01
        相关资源
        最近更新 更多