The reason why TryUpdateModel()
not updating your model binding state in the second Index
action is that you may binding instance of PersonModel
with property values of firstname
and lastname
still set to empty (or even null value).
You can use this setup to bind the model with TryUpdateModel
:
public async Task<ActionResult> Index([Bind(Include = "firstname, lastname")] PersonModel model)
{
if (TryUpdateModel(model))
{
// save changes with await
}
return View();
}
Or using FormCollection
as alternative:
public async Task<ActionResult> Index(FormCollection form)
{
var model = new PersonModel();
if (TryUpdateModel(model, string.Empty, new [] { "firstname", "lastname" }, null, form))
{
// save changes with await
}
return View();
}
However, I think it's better to setup a viewmodel which includes all required properties and bound from there, since TryUpdateModel()
method has security note you should pay attention to:
// Model
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
// Controller action
public async Task<ActionResult> Index(PersonViewModel model)
{
var data = new PersonModel();
data.FirstName = model.FirstName;
data.LastName = model.LastName;
// save changes with await
return View();
}
Related issues:
How do I edit a FormCollection value, and then use TryUpdateModel with the edited collection?
When and why do you use TryUpdateModel in asp.net mvc 2?
Using TryUpdateModel to save an object on Edit Post with FormCollection