JQuery和Razor控制器查看ActionResult

时间:2012-09-27 16:27:22

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

我有一个可以返回成功或错误页面的控制器:

[HttpPost]
public ActionResult File_post(HttpPostedFileBase file)
{
   if (...)
      return View("Success");
   else
      return View("Error");
}

那些成功和错误页面仅包含基本文本,并显示在Shared / _Layout.cshtml中。

在我的js中,我想调用返回视图定义的那些页面,但是我该怎么办呢?

我测试过:window.location.reload();
哪个有效,但它只重新加载实际的索引页面 如果我尝试:window.location.href = data.url;
它失败,因为页面 http:// xxx / xxx / File_post 不存在。
如果我这样做:$('#main').html(data);
页面看起来很好但内容是空的。

编辑:我正在使用jquery.fileupload,所以我有:

 <input id="fileupload" type="file" name="file" />

$('#fileupload').fileupload(
{
  done: function (e, data) {
    // Use the return View("Success")
  },
  fail: function (e, data) {
    // Use the return View("Error")
  }
});

在我的jqXHR.reponseText和data.result中有好的“成功”或“错误”的HTML,所以我想我需要用这个来填充页面但是如何?

有什么想法吗?非常感谢!

4 个答案:

答案 0 :(得分:1)

我找到了怎么做。 正如我在布局中<div id="main"> 我可以使用我的data.result来填充页面上的“成功”或“错误”消息。 所以我有:

done: function (e, data) {
  $('#main').html(data.result);
}

return PartialView("Success");

现在页面正确显示。

答案 1 :(得分:0)

您可以尝试使用此代码

$.ajax({
 type: "POST",
 url: Settings.YourUrl,
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
 alert("here" + data.d.toString());
});

在您的视图中,您可以添加此代码

var Settings= {
    YourUrl: '@Url.Action("Action","Controller")'
}

答案 2 :(得分:0)

当前操作只能处理POST请求。因此,您可以创建另一个操作来返回GET请求的视图。

实施例

public ViewResult Success()
{
   return View();
}

答案 3 :(得分:0)

您可以将statusCode更改为500或您需要的错误代码;

C#

[HttpPost]
public ActionResult File_post(HttpPostedFileBase file)
{
   if (...) 
   {
      return View("Success");
   }
   else
   {
      Response.StatusCode = 500;
      Response.TrySkipIisCustomErrors = true; 
      return View("Error");
   }
}

JS:

$('#fileupload').fileupload(
{
  done: function (e, data) {
    // Use the return View("Success")
  },
  fail: function (e, data) { // http status response != 200
    // Use the return View("Error")
  }
});