What's the better approach in changing the model's property value in controller
Which approach is more preferrable when changing just a single value in model? Aesthetically-speaking and performance-wise.
Looks clean(albeit with the overhead of pushing the entire model again to the View
):
ModelState.Remove("Name");
guestResponse.Nam开发者_开发百科e = "John";
return View(guestResponse);
Looks performant:
ModelState["Name"] = new ModelState { Value = new ValueProviderResult("Paul", null, null) };
return View();
If changing the model state dictionary is performant and can do this...
ModelState["Name"] = "George";
...I will use that over the first code(with Remove
and return View(guestResponse)
), but unfortunately, ModelState need to be assigned with ModelState and ValueProviderResult. It looks ugly to me.
Which one do you use when changing the model's property value(s) in controller?
The model properties are usually bound from the request values. So if I need to change a model value inside a controller action I simply call this action with the proper request string so that I don't have to do anything inside the controller. But to answer your question both approaches will perform well, it doesn't really matter which one you use.
精彩评论