ASP.NET Core: asp-* attributes use request payload over model?

后端 未结 2 1479
感动是毒
感动是毒 2021-01-20 00:56

It seems that in ASP.NET Core, the value in asp-* attributes (e.g. asp-for) is taken from the request payload before the model. Example:

P

2条回答
  •  孤独总比滥情好
    2021-01-20 01:09

    I believe this is the expected behavior/by design. Because when you submit the form, the form data will be stored to ModelState dictionary and when razor renders your form elements, it will use the values from the Model state dictionary. That is why you are seeing your form element values even when you are not passing an object of your view model to the View() method.

    If you want to update the input values, you need to explcitly clear the Model state dictionary. You can use ModelState.Clear() method to do so.

    [HttpPost]
    public IActionResult Create(YourviewModel model)
    {       
        ModelState.Clear();
        model.YourProperty = "New Value";
        return View(model);
    }
    

    The reason it uses Model state dictionary to render the form element values is to support use cases like, showing the previously submitted values in the form when there is a validation error occurs.

    EDIT : I found a link to the official github repo of aspnet mvc where this is confirmed by Eilon (asp.net team member)

    https://github.com/aspnet/Mvc/issues/4486#issuecomment-210603605

提交回复
热议问题