2014-09-18 123 views
0

我有簡單的頁面:阿賈克斯AspNetMvc錯誤請求

<div style="width:600px; margin-left:auto; margin-right:auto"> 
    <div style="background-color: lightgray"> 
     <h2>My Products</h2> 
    </div> 
    <p>Click the button to Get Products with an Ajax call</p> 

    <input id="btnAjax" name="btnAjax" type="button" value="Get Products" /> 
    <div id="products" style="background-color:lightskyblue"> 
     <div id='loadingmessage' style='display:none'> 
      loading... 
     </div> 
    </div> 
</div> 

和部分腳本:

@section Scripts { 
     @*@Scripts.Render("~/bundles/jqueryval")*@ 
    <script> 
     $('#btnAjax').click(function() { 
      $.ajax({ 
       url: '/Test/GetProducts', 
       contentType: 'application/html; charset=utf-8', 
       data: { id: 1 }, 
       type: 'GET', 
       dataType: 'html' 
      })  
      .success(function (result) { 
       $('#products').html(result); 
       $('#loadingmessage').hide(); 
      }) 
      .error(function (xhr, status, throwError) { 
       alert(status); 
      })   
     }); 
     </script> 
    } 

中的TestController方法名的GetProducts(INT ID):

public PartialViewResult GetProducts(int id) 
    { 
     var listOfCourses = db.Courses.ToList(); 
     Task.Delay(9000000); 
     if(id == 1) 
      throw new Exception("something bad"); 

     return PartialView("_GetProducts", listOfCourses); 
    } 

是任何在按鈕(#btnAjax)中設置'id'的方法並將其扔到ajax腳本中?例如:

<input id="btnAjax" name="btnAjax" type="button" value="Get Products" data:id="1" /> 

,然後在AJAX腳本

data: { id: $(this).id 

讀它?

第二個問題是如何,我可以從異常錯誤事件得到消息錯誤(「壞事」)

+0

「第二個問題是我如何從錯誤事件中的異常中獲取消息錯誤(」有些不好「)」我不理解這個問題,對不起。 – 2014-09-18 15:45:18

+0

錯誤事件: .error(函數(XHR,狀態,throwError){ HERE } 怎麼這裏我可以把與法的GetProducts(INT ID) – W92 2014-09-18 15:47:23

回答

1

將其設置爲數據屬性例如data-id

<input id="btnAjax" name="btnAjax" type="button" value="Get Products" data-id="1" />

,並閱讀它,你可以使用以下兩種:

$("input#btnAjax").attr("data-id")

$("input#btnAjax").data("id")

第二個選項是最先進的這樣做的日期方式。

編輯:

關於第二個問題,你需要返回JSON例如

public ActionResult GetProducts(int id) 
{ 
    var listOfCourses = db.Courses.ToList(); 

    Task.Delay(9000000); 

    if (id == 1) 
    { 
     Response.StatusCode = (int)HttpStatusCode.BadRequest; 
     return Json(new { ErrorMessage = "Test" }, JsonRequestBehavior.AllowGet); 
    } 

    return PartialView("_GetProducts", listOfCourses); 
} 

我認爲上面應該工作(我沒有機會嘗試這個我自己)。通過將狀態碼設置爲錯誤代碼(而不是200狀態確定),您應該在JavaScript中的AJAX代碼中點擊error函數。

我不是100%確定這一點,但肯定我的答案的第一部分應該爲你工作。

+0

無法隱式轉換類型「的System.Web異常信息提示。 Mvc.JsonResult'改爲'System.Web.Mvc.PartialViewResult' – W92 2014-09-18 15:57:32

+1

檢查我的代碼,我在方法簽名中使用'public ActionResult .....',這意味着你可以傳遞'JSON'或'PartialViewResult' – 2014-09-18 15:58:57

+0

感謝您的幫助:-)這個經驗在世界上最值得:-)! – W92 2014-09-18 16:14:37