ASP.NET MVC - JSON + HttpException
I'm trying to return an error page indicating that the user couldnt be found and therefore I throw a HttpException with status code 404, however for some reason it wont redirect to the error page? - Is there some sort of trick to handle error pages with JSON that I should be aware of?
My current code:
public ActionResult Details(int id)
{
User userToGet = _session.Query(new GetUserById(id));
if(userToGet == null)
{
throw new HttpException(404, "User not found");
}
DetailsUserViewModel userToViewModel = AutoMapper.Mapper.Map<User, DetailsUserViewModel>(userToGet);
return Json(new
{
HTML = RenderPartialViewToString("Partials/Details", userToViewModel)
}, JsonRequestBehavior.AllowGet);
}
Thanks in advance!
Update - Some more code:
// MyJs.js
function openBox(object) {
$("body").append("<开发者_开发技巧;div id='fadeBox'></div><div id='overlay' style='display:none;'></div>");
$("#fadeBox").html("<div style='position:absolute;top:0;right:0;margin-right:2px;margin-top:2px;'><a id='closeBox' href='#'>x</a></div>" + object["HTML"])
$("#fadeBox").fadeIn("slow");
$('#wrapper').attr('disabled', 'disabled');
$("#overlay").show();
jQuery.validator.unobtrusive.parse('#mybox') /* Enable client-side validation for partial view */
}
// List.cshtml
@model IEnumerable<MyDemon.ViewModels.ListUsersViewModel>
<table style="width:100%;">
<tr style="font-weight:bold;">
<td>UserId</td>
<td>UserName</td>
</tr>
@foreach (var user in Model)
{
<tr>
<td>@user.UserId</td>
<td>@user.UserName</td>
<td>@Ajax.ActionLink("Details", "details", "account", new { id = @user.UserId }, new AjaxOptions() { HttpMethod = "GET", OnSuccess = "openBox" })</td>
</tr>
}
</table>
Your controller action is very strange. You are returning a JSON object but which contains HTML. That's not necessary. If you intend to return HTML then return a partial view. JSON brings no value in your situation:
public ActionResult Details(int id)
{
User userToGet = _session.Query(new GetUserById(id));
if(userToGet == null)
{
return PartialView("404");
}
DetailsUserViewModel userToViewModel = AutoMapper.Mapper.Map<User, DetailsUserViewModel>(userToGet);
return PartialView("~/Views/Home/Partials/Details.ascx", userToViewModel);
}
If you want to use JSON then work with objects:
public ActionResult Details(int id)
{
User userToGet = _session.Query(new GetUserById(id));
if(userToGet == null)
{
return Json(new { user = null }, JsonRequestBehavior.AllowGet);
}
DetailsUserViewModel userToViewModel = AutoMapper.Mapper.Map<User, DetailsUserViewModel>(userToGet);
return Json(new { user = userToViewModel }, JsonRequestBehavior.AllowGet);
}
and then:
$.getJSON('<%= Url.Action("Details") %>', { id: '123' }, function(result) {
if (result.user == null) {
alert('user not found');
} else {
// do something with result.user
}
});
精彩评论