4

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?

Mr Lahey
  • 656
  • 3
  • 15
  • 31

2 Answers2

5

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);
moribvndvs
  • 42,191
  • 11
  • 135
  • 149
  • Whats the best way to do a plain insert instead of TryUpdateModel? Is there an equivalent so I can use mostly the same code with the form collection? – Mr Lahey Jun 19 '12 at 15:47
  • Im not sure what you mean by plain insert. – moribvndvs Jun 19 '12 at 16:11
  • I want to insert a new record, rather than update an existing one. So something like tryInsertModel (made that up but you get the idea). – Mr Lahey Jun 19 '12 at 16:21
0

you can use updateModel() provided by asp.net mvc to get all model values from formcollection key value pair and map to your database model provided your formcollection key matches the model parameters i.e

public ActionResult CreateUser(FormCollection fc)
 {

    UserModel usermodel= new UserModel ();

    if(TryUpdateModel(usermodel,fc.ToValueProvider()))

        UpdateModel(usermodel, fc.ToValueProvider());

  return View("UserView"); 
}
Usman Khalid
  • 140
  • 1
  • 8