簡體   English   中英

JQuery和Razor控制器查看ActionResult

[英]JQuery and Razor Controller View ActionResult

我有一個可以返回成功或錯誤頁面的控制器,如下所示:

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

這些成功和錯誤頁面僅包含基本文本,並顯示在Shared / _Layout.cshtml中。

在我的js中,我想調用由return View定義的那些頁面,但是我該怎么做呢?

我測試了: 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中,有很好的“ Success”或“ Error” html,因此我認為我需要用此填充頁面,但是如何?

有任何想法嗎 ? 非常感謝 !

我找到了怎么做。 正如我在版式中有一個<div id="main">我可以使用data.result來用“成功”或“錯誤”消息填充頁面。 所以我有 :

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

return PartialView("Success");

現在,該頁面已正確顯示。

您可以嘗試使用此代碼

$.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")'
}

當前操作只能處理POST請求。 因此,您可以創建另一個操作以返回GET請求的視圖。

例如

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

您可以將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")
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM