0

I have a asp.net mvc controller and I am facing a strange problem. When I tried to bind the model using Bind with whitelisting items it is working fine but when I tried to bind using the TryUpdateModel with include properties the same thing is not working. My code is pretty much standard.

public async Task<ActionResult> Index([Bind(include="firstname,lastname")]PersonModel model){
  .......
}

public async Task<ActionResult> Index(){
   var model = new PersonModel();
   var isBinding = TryUpdateModel(model,includeProperties:new[]{"firstName","lastname"})
  .......
}

Even though it is not binding, isBinding is set to true. Can any please suggest me why TryUpdateModel is not working but Bind is working. Thank you

LilRazi
  • 690
  • 12
  • 33

1 Answers1

0

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

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • Not sure why you are suggesting to use both Bind and TryUpdateModel on same program(Example 1). https://odetocode.com/blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx article suggest to use either Bind or TryUpdateModel – LilRazi Aug 30 '18 at 00:36