【问题标题】:Altering the ASP.NET MVC 2 ActionResult on HTTP post在 HTTP 帖子上更改 ASP.NET MVC 2 ActionResult
【发布时间】:2010-05-02 20:29:46
【问题描述】:

我想在返回视图之前对属性进行一些处理。如果我将在下面的 HttpPost ActionResult 方法中返回的 appModel.Markup 设置为“已修改”,它仍然会在表单上显示“原始”。为什么我不能在 HttpGet ActionResult 方法中修改我的属性?

    [HttpGet]
    public ActionResult Index()
    {
        return View(new MyModel
        {
            Markup = "original"
        });
    }

    [HttpPost]
    public ActionResult Index(MyModel appModel)
    {
        return View(new MyModel
        {
            Markup = "modified"
        });
    }

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-2


    【解决方案1】:

    因为“原始”存储在 ModelState 中。在 MVC 端收集表单值时,它们存储在 ModelState 对象中。您可能使用了Html.TextBox 助手。当您在 POST 之后重新创建视图时,它会首先查找 ModelState,如果有已发布的值,它会设置此值。模型对象中的值不再计算在内。

    其中一种解决方案是遵循 POST-REDIRECT-GET 模式。首先 POST,对数据做一些事情,然后重定向:

    [HttpPost]
    public ActionResult Index(MyModel appModel)
    {
        //do something with data
        return RedirectToAction("Index");
    }
    

    如果你想在重定向之间传递一些东西,你可以使用TempData:

    [HttpPost]
    public ActionResult Index(MyModel appModel)
    {
        //do something with data
        TempData["Something"] = "Hello";
        return RedirectToAction("Index");
    }
    
    [HttpGet]
    public ActionResult Index()
    {
        var something = TempData["Something"]; //after redirection it contains "Hello"
    }
    

    重定向后,ModelState 消失了,因此没有值可以覆盖。当您在浏览器中按 F5 时,POST-REDIRECT-GET 模式还有助于消除表单重新发布的影响。

    【讨论】:

    • 谢谢。我还找到了一个使用 ViewData 的解决方案,但不如您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    相关资源
    最近更新 更多