2011-04-07 17 views
1

我有2個問題,在第一個,我得到一個列表,我想如果在C#代碼(控制器)中的excetpion有可能對一個視圖(錯誤視圖)並顯示一個特定的div。如何在.error中獲取視圖。 ? HTMLASP.NET MVC中使用jQuery的異常管理

<div><a href="#" class="MnuCustomerList">List</a></div> 

jQuery的

$(".MnuCustomerList").click(function() { 
    var jqxhr = $.post("/Customer/List", function (data) { 
     $('#rightcolumn').html(data); 
    }) 
    .success(function() { alert("success"); }) 
    .error(function() { alert("error"); }) 
    .complete(function() { alert("complete"); }); 
}) 

;

控制器:

public PartialViewResult List() 
{ 
    throw new Exception("myexception"); 
    return PartialView("List"); 
} 

第二個問題: 我有一個表格

@model MyModel 
@using (Html.BeginForm("Save", "Customer", FormMethod.Post)) 
{ 
    <table style="width:100%;"> 
    <tr> 
     <td>Code</td> 
     <td>@Html.TextBoxFor(m => m.Customer.Code, new { id = "tbCode" })</td> 
    </tr> 
    <tr> 
     <td>LastName</td> 
     <td>@Html.TextBoxFor(m => m.Customer.LastName, new { id = "tb", maxlength = 50, style = "width:40%;" })</td> 
    </tr> 
    <tr> 
     <td colspan="2"><input type="submit" value="A submit button"/></td> 
    </tr> 
    </table> 
} 

在Controller中,我檢查,如果代碼已經存在,如果是CustomerException( 「代碼存在」)。

我的問題,是有可能使用jQuery,但仍然使用這種格式的意思是與模型,並通過一個價值像下面

$.ajax({ 
    type: "POST", 
    url: "/Customer/Save", 
    data: { 
     id: $('#Id').val(), 
     firstName: $('#FirstName').val(), 
     lastName: $('#LastName').val(), 
     isEnable: $('#IsEnable').attr('checked')   
    }, 
    success: function (html) { 
     $("#ContentDataSection").html(html); 
    }, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { } 
}); 

由於樣品沒有得到一個值後這種形式,

回答

6

只有在發出ajax請求時出現錯誤,纔會觸發錯誤回調。如果服務器端發生錯誤,則需要將數據傳回客戶端(使用Json格式是個不錯的選擇),指出服務器端存在故障並在成功回調中處理它。

編輯添加代碼展示瞭如何響應代碼設置爲500,因此它可以在錯誤調用每萊恩的評論後面進行處理:

控制器動作:

public ActionResult FiveHundred() 
{ 
    Response.StatusCode = 500; 
    return Json(new {Error = "Uh oh!"}); 
} 

的Javascript:

$.ajax({ 
    url: "/home/fivehundred", 
    type: "POST", 
    success: function(data) { 
     // handle normally 
    }, 
    error: function(data) { 
     alert("error " + data.Error); 
    } 
}); 
+0

當我發佈我的表單時,我檢查是否存在代碼,存在我想要:1.顯示消息客戶端2.停止發佈此第二點是否有可能? – 2011-04-07 20:09:02

+0

您可以將狀態碼始終設置爲500(或任何其他錯誤代碼)以觸發錯誤回調來處理json響應。 – Ryan 2011-04-07 20:10:31

+0

@瑞安你有樣品如何實現這個? – 2011-04-07 20:18:53