开发者

Altering the ASP.NET MVC 2 ActionResult on HTTP post

开发者 https://www.devze.com 2022-12-28 17:22 出处:网络
I want to do some processing on a attribute before returning the view. If I set the appModel.Markup returned in the HttpPost ActionResult method below to \"modified\" it still says \"original\" on the

I want to do some processing on a attribute before returning the view. If I set the appModel.Markup returned in the HttpPost ActionResult method below to "modified" it still says "original" on the form. Why cant I modify my attribute in a HttpGet ActionResult method?

    [HttpGet]
    public ActionResult Index()
    {
        return View(new MyModel
        {
            Markup开发者_高级运维 = "original"
        });
    }

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


Because "original" is stored in ModelState. When form values are collected on MVC side, they are stored in ModelState object. You propably used Html.TextBox helper. When you recreate view after POST, it looks up into ModelState first and if there is posted value, it sets this value. Value in model object doesn't count anymore.

One of the solutions is to follow POST-REDIRECT-GET pattern. First POST, do something with data and then redirect:

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

If you want to pass something between redirects, you can use 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"
}

After redirect, ModelState is gone, so the is no value to override. POST-REDIRECT-GET pattern also helps to get rid of form reposting effect when you press F5 in browser.

0

精彩评论

暂无评论...
验证码 换一张
取 消