Mvc retain values after postback

2019-04-02 07:08发布

I have a simple TestController class and User model:

public class TestController : Controller
{
    public ActionResult TestAction()
    {
        return View();
    }

    [HttpPost]
    public ActionResult TestAction(User user)
    {
        return View();
    }
}

public class User
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
}

This is my form:

enter image description here

As far as I know MVC is stateless and it does not have a viewstate concept. But after posting the data to my controller and when I return the view, all my data is there. I expect empty fields but they are all filled with the posted data. I could not understand how MVC knows the values after postback?

2条回答
一夜七次
2楼-- · 2019-04-02 07:54

You Need to use ModelState.Clear()

public class TestController : Controller
{
    public ActionResult TestAction()
    {
        return View();
    }

    [HttpPost]
    public ActionResult TestAction(User user)
    {
        ModelState.Clear()
        return View();
    }
}
查看更多
小情绪 Triste *
3楼-- · 2019-04-02 08:02

@stephen.vakil

When you return a View from an HttpPost the assumption is that you are handling an error condition. It will keep the posted data in the ModelState and re-fill the data on the page so that the user can correct it.

查看更多
登录 后发表回答