【问题标题】:cshtml view not renderingcshtml视图不呈现
【发布时间】:2014-07-09 12:42:44
【问题描述】:

我正在使用带有剃须刀引擎的 ASP.net MVC。

我有一个带有按钮的页面,当单击该按钮时,我使用 Ajax 在我的控制器中调用 ActionResult。 Ajax 调用:

 $.ajax({
     type: "GET",
     url: "/Home/Review",
     success: function (data) {
         //alert("yay");
     }
});

我的ActionResult 方法很好,但是它不会加载指定的视图。 代码:

public ActionResult Review()
{
    return View();
}

当前视图是 Index.cshtml,当 Review() 被点击时,我希望 Review.cshtml 在屏幕上呈现。 (它应该呈现为完整视图,而不是 Index.cshtml 中的部分视图)

我试过了-return View("Review");return View("Review.cshtml");return View("..\Views\Home\Review.cshtml);

我无法使用 - tml.BeginForm("Action", "Controller", FormMethod.Post);(请参阅我的其他问题 MVC submit button not firing

【问题讨论】:

  • success回调函数的data参数,应该包含来自服务器的响应。
  • 您想在 Index 中包含 Review.cshtml 的内容吗?如果不是,为什么要进行 ajax 调用?
  • @NicoD 不,我想加载评论而不是索引......就像导航到不同的页面
  • 只需将表单提交到特定的action Html.BeginForm("Action", "Controller", FormMethod.Post);或在这种情况下使用链接。不需要 ajax。
  • 刚刚编辑了帖子以说明为什么我不能使用它。另外我稍后会发送一些数据,所以无论如何都需要 ajax

标签: c# ajax asp.net-mvc razor


【解决方案1】:

将响应直接写入屏幕

success: function (data) {
   document.write(data)  }

【讨论】:

【解决方案2】:

在 ajax 之后,你应该渲染一个局部视图以将返回结果添加到主视图(索引)。

Index.cshtml

$.ajax({
   type: "GET",
   url: "/Home/Review",
   success: function (data) {
       $("#container").html(data);
       //alert("yay");
   }
...

<div id="container"></div>

控制器

public ActionResult Review()
{

    return PartialView();
}

如果你想在 ajax 之后重定向,你可以使用类似下面的东西:

Index.cshtml

$.ajax({
   type: "GET",
   url: "/Home/Review",
   success: function (data) {
       window.location.href = data.url;
   }
...

控制器

public ActionResult Review()
{

    return Json(new { url = "some url" }, JsonRequestBehavior.AllowGet); 
}

【讨论】:

  • 那是部分视图,我想渲染一个完整视图
  • @DNKROZ,如果要渲染整页,为什么要使用ajax post?
  • 因为我使用的是 jQuery UI 按钮并且点击处理程序阻止 Html.BeginForm 工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
相关资源
最近更新 更多