user1929393
user1929393

Reputation: 4277

MVC models and updating 1 field in db

Is it possible to update 1 field in a model, without passing all the other model items back to the controler?

For example, if my model has 4 items (id, firstname, lastname, address)

If my xxx.cshtml file only has 1 editable field for firstname, do I also need to include all 4 items in the httpost? It makes no sense, if I only want to edit 1 field, yet my record contains may contain many (ie.16) fields in the model.

Currently, I am querying a record, grabbing only 2 fields, the id, and firstname to display and edit. When I save, it does not appear to save.

Thanks.

Upvotes: 0

Views: 1978

Answers (1)

James Harris
James Harris

Reputation: 1914

What your after is TryUpdateModel.

It will only update properties for which the ModelBinder finds a form value.

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.108).aspx

You use entityframework to get your model from the database, then call TryUpdateModel (you can also optionally pass in a whitelist of properties to be updated, this prevents malicious users from changing other properties in your model by adding form values).

Check the return value to see if a validation error has occured.

Example:

[HttpPost]
public ActionResult Edit(int id, FormCollection form)
{
   var model=_db.Widgets.Find(id);

   //make sure that the model exists in our database
   if (model==null)
   {
      return HttpNotFoundResult();
   }


   if (TryUpdateModel(model,new string[] {"Property1","Property2"}))
   {
      _db.SaveChanges();
      return RedirectToAction("Index"); //or wherever you want to go
   }
   else  //TryUpdateModel returns false on a validation error
   {
      //return to the view and give the user a chance to fix the validation error(s)
      return View("Edit",model);
   }


}

Upvotes: 2

Related Questions