【问题标题】:load another view on ajax post在 ajax 帖子上加载另一个视图
【发布时间】:2017-08-16 15:49:52
【问题描述】:

我有一个视图 UserInformation,我在其中填写了一些与用户相关的信息,并使用 ajax 帖子将这些信息发布到另一个视图“AnotherView”。

现在我想在动作方法“AnotherView”中获取这些输入,并使用一些数据模型加载视图“AnotherView”。

当我从视图 UserInformation 到操作方法 "AnotherView" 执行 Ajax Post 时,它会执行操作方法 "AnotherView",但它仍然显示视图 UserInformation

从视图 UserInformation

调用 Ajax
$.ajax({
    url: '/somecontroller/AnotherView/',
    data: {
        name: $.trim($('#mgr').val()),
        id: $('#id').val(),
        email: $.trim($('#hdnMgrmail').val())
    },
    cache: false,
    type: "POST",
    dataType: "html",
    success: function (data,
        textStatus, XMLHttpRequest) {
        alert('ok');
    }
});


[HttpPost]
public ActionResult AnotherView(few parametrs that is coming here)
{
      //create model using input params
      return View(with some model);
}

【问题讨论】:

  • 您需要在成功回调中将 AnotherView() 方法返回的部分视图添加到 DOM - 例如$(someElement).html(data);
  • 你的success函数中的data变量是否不包含AnotherView的HTML内容?您需要做的就是将此内容放在您需要的地方。
  • 我必须加载完整视图而不是部分视图
  • 那就不要使用ajax了!
  • Ajax.BeginForm() 只是$.ajax() 的一个包装器。如果您想显示不同的视图,请进行正常的提交和重定向。

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


【解决方案1】:

由于您的目标控制器操作返回 ActionResult,因此您可以预期它将返回呈现的 HTML(以及发生的任何数据绑定)。

所以你的成功回调的data参数实际上将包含这些内容,所以你可以简单地使用一个jQuery选择器来确定你想要使用html()函数输出它的位置:

success: function (data, textStatus, XMLHttpRequest) {
    // data is your HTML content
    $(...).html(data);
}

值得注意的是,如果您打算返回一小部分内容而不是任何其他内容(例如布局或其他相关视图),则可能需要考虑使用 PartialView() 方法:

[HttpPost]
public ActionResult AnotherView(...)
{
     return PartialView(...);
}

更新

由于在 cmets 中提到最好完全刷新页面,如果是这种情况,那么您可以考虑简单地提交一个发布到目标操作的表单,并且提交事件将处理导航(并返回整个动作):

<form action='/somecontroller/AnotherView/' method='post'>
    <input id='mgr' name='name' />
    <input id='id' name='id' />
    <input id='hdnMgrmail' name='email' />
    <input type='submit' />
</form>

【讨论】:

  • 谢谢rion,让我试一试。再查询一次,如果我使用表单操作帖子,我相信我不必对操作方法进行任何更改。是否正确?跨度>
  • 正确。如果您提交表单,则无需返回PartialView(),因为它将在 POST 完成后返回整个视图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 2015-11-23
相关资源
最近更新 更多