Exception management in ASP.NET MVC using jquery
I have 2 question, in the first one, I get a list, I'd like if excetpion in C# code (controller) has the possibility to a View (an error view) and display it a specific div. How can I get the view in the .error. ? HTML
<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"); });
})
;
Controller:
public PartialViewResult L开发者_开发百科ist()
{
throw new Exception("myexception");
return PartialView("List");
}
Second question : I have a form
@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>
}
In the Controller, I check if the code already exist, if yes CustomerException("Code exist").
My questions, is it possible to post this form using jQuery BUT still using this format that's mean with the model and NOT get one value by one value like the sample below
$.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) { }
});
Thanks,
The error callback is only going to fire if there is an error in making the ajax request. If an error occurs server side, you'll need to pass data back (in Json format would be a good choice) to the client indicating there was a failure server side and handle it in the success callback.
Edit to add code showing how to set response code to 500 so it can be handled in the error call back per Ryan's comment:
Controller action:
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);
}
});
精彩评论