【问题标题】:Render Partial View with Object Model using jquery / Ajax使用 jquery / Ajax 使用对象模型渲染部分视图
【发布时间】:2013-08-15 15:28:23
【问题描述】:

我当前的代码看起来像

<!-- some html -->
{
    // some code
    @Html.Partial("~/Views/AdminUser/Main.cshtml", Model.AdminUserModel)
}

但是,我需要将其改为 ajax 调用。如何在调用中包含模型的情况下进行 jquery ajax 调用?

【问题讨论】:

  • 您可以做的是使用 url 查询进行 ajax 调用。根据您的查询字符串设置变量。
  • 该解决方案的问题是模型可能很大。主要需要知道如何传递模型。
  • 是否认为您可以让 ajax 调用包含模型的 json(字符串化?)版本,然后在后端将模型放回对象中?不太清楚怎么做。

标签: c# jquery asp.net-mvc html.renderpartial


【解决方案1】:

我的做法是通过 id 进行 ajax 调用:

$.ajax({
    url: "@(Url.Action("Action", "Controller", new { id = "----" }))/".replace("----", id),
    type: "POST",
    cache: false,
    async: true,
    success: function (result) {
         $(".Class").html(result);
    }
});

然后在你的控制器中设置动作

public PartialViewResult Action(string id)
{
     //Build your model
     return PartialView("_PartialName", model);
}

如果你确实需要通过ajax将模型传递给控制器​​,如果你创建一个与模型具有相同字段的jquery对象并字符串化并传递它,它将正确通过。

var toSend = {};
toSend.ID = id;
toSend.Name = name; 

等,然后在ajax调用中

data: JSON.stringify(toSend),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2011-06-18
    • 2015-01-29
    • 2011-04-08
    • 2015-09-18
    • 2020-12-21
    • 2013-10-08
    相关资源
    最近更新 更多