Mvc retain values after postback

随声附和 提交于 2020-01-01 07:06:28

问题


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:

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?


回答1:


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



回答2:


@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.



来源:https://stackoverflow.com/questions/39838799/mvc-retain-values-after-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!