开发者

Weird MVC Issue

开发者 https://www.devze.com 2023-03-12 11:00 出处:网络
I have this code and I can\'t understand why it works this way I have a model and view which is arbitrary and a very simple (but weird) controller

I have this code and I can't understand why it works this way

I have a model and view which is arbitrary and a very simple (but weird) controller

Here is my controller:

public partial class RouteController : Controller
{
    [HttpGet]
    public virtual ActionResult Create()
    {
        Create create = new Create();
        return View("Create", create);
    }

    [HttpPost]
    public virtual Act开发者_开发技巧ionResult Create(Create route)
    {
        return Create();
    }
}

The first create method loads the view as normal. When the view posts back it runs the 2nd action which runs the first (as expected). The wierd part is the view is (re-)loaded with my previously entered data with errors (if any). I dont understand this because my model is empty. I was expecting it to post back with the same form as if it was loaded for the first time but with errors possibly.

Please explain.


That's the normal behavior of HTML helpers and it is by design. They first look at values contained in the ModelState and after that in the actual model. If you intend to modify some values on the model in a POST action you need to remove them from modelstate first:

For example:

[HttpPost]
public virtual ActionResult Create(Create route)
{
    ModelState.Remove("SomeProperty");
    route.SomeProperty = "some new value";
    return View(route);
}

If you intend to completely modify everything as in your example you could clear the modelstate entirely:

[HttpPost]
public virtual ActionResult Create(Create route)
{
    ModelState.Clear();
    return Create();
}

Another possibility is to write your own TextBoxFor, HiddenFor, CheckBoxFor, ... helpers that will use the value in the model and not the one in the model state. Or yet another (non-recommended) possibility:

<input type="text" name="SomeProperty" value="@Model.SomeProperty" />

Of course in this case client validation among other things provided by the standard helpers won't work.

0

精彩评论

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