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?
You can create your own source by creating a
NameValueCollectionwith your values, then using that to create aFormCollection, and then you can use that form collection as the value provider directly.Also,
FormCollectionhas anAddmethod, where you can just add values directly.If you are binding a flat model (say,
Userin 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: