ASP.NET MVC - JSON + HttpException

时间:2011-01-30 10:47:42

标签: asp.net asp.net-mvc

我正在尝试返回一个错误页面,指出用户无法找到,因此我抛出一个状态代码为404的HttpException,但是由于某种原因它不会重定向到错误页面? - 是否有某种技巧来处理我应该注意的带有JSON的错误页面?

我目前的代码:

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);
}

提前致谢!

更新 - 更多代码:

// 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>

1 个答案:

答案 0 :(得分:3)

你的控制器动作很奇怪。您正在返回一个包含HTML的JSON对象。这不是必要的。如果您打算返回HTML,则返回部分视图。 JSON在您的情况下没有任何价值:

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);
}

如果你想使用JSON,那么使用对象:

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);
}

然后:

$.getJSON('<%= Url.Action("Details") %>', { id: '123' }, function(result) {
    if (result.user == null) {
        alert('user not found');
    } else {
        // do something with result.user
    }
});