【问题标题】:How to implement PRG pattern and still use Ajax post response in asp mvc 4?如何在 asp mvc 4 中实现 PRG 模式并仍然使用 Ajax 后响应?
【发布时间】:2014-06-11 21:25:22
【问题描述】:

我们的 MVC 控制器继承自删除响应的自定义控制器(对于 PRG 模式):

protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
    if (filterContext.HttpContext.Request.HttpMethod != @"GET")
    {
        Response.Clear();
    }
}

在客户端,我正在做一个简单的保存到数据库:

        var success = function (result) {
             showNotification(result.Message, 'success', 3000);
             hrp.load();
        }


        var inputArray = $(hoursForm + ' [name], ' + hoursFormId);
        postAjaxArrayData('RoundingPolicies/SaveHoursRoundingPolicy', inputArray, success);

这使得控制器很好,保存,但由于我们正在清除响应,success() 没有从以下位置返回结果:

public void SaveHoursRoundingPolicy(HoursRoundingPolicyViewModel hoursRoundingPolicyViewModel) {

   // Save

    var json = new {
        hoursRoundingPolicyViewModel.RoundingPolicyId,
        hoursRoundingPolicyViewModel.Name,
        Message = String.Format("Successfully Saved - ({0}) {1}", hoursRoundingPolicyViewModel.RoundingPolicyId, hoursRoundingPolicyViewModel.Name)
    };
    return Json(json);
}

我们如何仍然实现 PRG 模式(通过清除 POST 上的响应)但仍然从 Ajax POST 返回结果?我可以在 OnResultExecuted() 中区分这两者吗?

我想这对于任何使用带有 MVC 的 PRG 模式的人来说都是一个相当普遍的场景,有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 http-post


    【解决方案1】:

    为什么要清除响应?这不是 PRG 的一部分……至少在我的经验中不是。

    根据我使用 PRG 的经验,您接受该帖子,当/如果它成功,您只需重定向到另一个导致 GET 的操作,无需清除响应。

    遵循上述模式仍然可以让您的 AJAX 帖子像普通帖子一样工作

    // Simple implementation of PRG    
    [AcceptVerbs(HttpVerbs.Post)
    public ActionResult Something(int value) {
       return RedirectToAction("SomethingElse");
    }
    
    public ActionResult SomethingElse() {
       return View();
    }
    
    // Simple implementation of standard post
    [AcceptVerbs(HttpVerbs.Post)
    public ActionResult SomethingAjax(int value) {
       return Json(value);
    }
    

    为 filterContext.Result 比较编辑 这应该检查 Action 的返回类型,并且当它是 JsonResult 时不将 Response.Clear() 应用于 Response

    protected override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if (filterContext.HttpContext.Request.HttpMethod != @"GET" && !(filterContext.Result is JsonResult))
        {
            Response.Clear();
        }
    }
    
    // Simple implementation of standard post
    [AcceptVerbs(HttpVerbs.Post)
    public JsonResult SomethingAjax(int value) {
       return Json(value);
    }
    

    【讨论】:

    • 谢谢 Anthony,所以只要我们重定向 ActionResults,我们就可以为任何 JSON 类型的请求/响应返回响应?我们可以避免重复提交、刷新等吗?我也有同样的想法,但想听听其他人的想法......
    • 是的,因为一旦发生重定向,它就会从重定向的 Action 请求 GET。我想作为另一种选择,你可以做 JsonResult 返回类型,并可能在你的 OnResultExecuted 中处理它(没有任何代码示例,但如果你想看到它可以做一些事情)并且你不能做清除那里(如果您死心塌地使用 Response.Clear)
    • 居然加了检查Action Result类型的代码,比我想象的要容易
    猜你喜欢
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 2018-06-16
    • 2012-10-19
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多