Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# UpdateModel with custom data instead of FormCollection

For reference this is in a C# MVC2 website.

I'm looking to save a data using a Model in my database, but I need to do it with custom data rather than the FormCollection I am used to. Here is how I typically do it:

TryUpdateModel(userToUpdate, new string[] { "ID", "Name", "Age", "Gender" }, form.ToValueProvider());

// Model Validation is here, no need to see it so removed to save space

if (ModelState.IsValid)
{
     dbu.SaveChanges();
}

How do I go about replacing the form.ToValueProvider() with custom data? How should it be created/formatted?

like image 812
Mr Lahey Avatar asked Nov 04 '25 12:11

Mr Lahey


1 Answers

You can create your own source by creating a NameValueCollection with your values, then using that to create a FormCollection, and then you can use that form collection as the value provider directly.

Also, FormCollection has an Add method, where you can just add values directly.

var values = new NameValueCollection { { "ID", "1" }, {"Name": "Bob"} }; // etc.
var collection = new FormCollection(values);

// or...
// var collection = new FormCollection();
// collection.Add("ID", "1");
// collection.Add("Name", "Bob");
// etc.

TryUpdateModel(userToUpdate, new string[] { "ID", "Name", "Age", "Gender" }, form);

If you are binding a flat model (say, User in this example), the above sample will be enough. However, if your fields have a prefix (this might be the case if you are doing a deep model binding), separate the prefix with a dot:

var collection = new FormCollection();
collection.Add("User.ID", "1");
collection.Add("User.Name", "Bob");

// Binds to fields with the prefix "User"
TryUpdateModel(userToUpdate, "User", new string[] { "ID", "Name", "Age", "Gender" }, null, form);
like image 177
moribvndvs Avatar answered Nov 07 '25 11:11

moribvndvs