Is there a special case when we should use ModelState.IsValid and not TryUpdateModel or vice versa?

I am really confused about choosing ModelState.IsValideither TryUpdateModelfor use in action methods Create, Editand Delete(HTTP-POST).

Is there a special case when we should use ModelState.IsValidinstead TryUpdateModelor vice versa?

+3
source share
1 answer
Function

TryUpdateModelreturns ModelState.IsValid. This is one thing. Using, TryUpdateModelyou can update an existing object with the values ​​specified on the form. But when you create a new one, you have two ways:

[HttpPost]
public function Create(Model model)
{
      //ModelState is already populated, binding of form values to Model is done.
}

or

[HttpPost]
public function Create()
{
    //ModelState is not populated yet
    var model = new Model();
    TryUpdateModel(model);
    //ModelState is populated here, after Model values population.
}

When you upgrade an existing model, it might look like this:

[HttpPost]
public function Update(int id)
{
    var model = Repository.Get(id);
    TryUpdateModel(model);
    if (ModelState.IsValid) 
        Repository.Save();
}

or

[HttpPost]
public function Update(int id)
{
    var model = Repository.Get(id);
    if (TryUpdateModel(model))
        Repository.Save();
}

It is the same.

+3
source

Source: https://habr.com/ru/post/1792713/


All Articles