Preventing unintended updates in MVC With Example
Sardar Mudassar Ali Khan
Posted on July 4, 2023
To prevent unintended updates in MVC, you can implement various measures to validate and restrict the properties that can be updated. Here's an example that demonstrates some common techniques:
- Use View Models: Instead of binding directly to the actual model, use view models that only contain the properties required for editing. This allows you to have fine-grained control over the properties that can be updated.
public class PersonEditViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
- Apply Model Binding Whitelisting:
Explicitly specify the allowed properties during model binding to restrict the properties that can be updated. This can be done using the
[Bind]
attribute in the action method parameter.
[HttpPost]
public ActionResult Edit([Bind(Include = "Id, Name, Age")] PersonEditViewModel viewModel)
{
// Rest of the code...
}
By specifying the included properties in the Include
parameter, you explicitly whitelist only those properties that are allowed for binding.
- Use Input Validation:
Apply input validation to ensure that the submitted values are valid. You can use data annotations, such as
[Required]
,[Range]
, or custom validation attributes, to validate the properties of the view model.
public class PersonEditViewModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(1, 150)]
public int Age { get; set; }
}
By applying validation attributes, you can enforce constraints on the submitted values and prevent unintended updates due to invalid data.
- Retrieve the Original Model from a Trusted Source: When updating the model, retrieve the original model object from a trusted source, such as the database, rather than relying solely on user-submitted data. This ensures that the model's sensitive properties are not modified unintentionally.
[HttpPost]
public ActionResult Edit(PersonEditViewModel viewModel)
{
if (ModelState.IsValid)
{
var person = GetPersonById(viewModel.Id); // Retrieve the original model from a trusted source
// Update only the allowed properties
person.Name = viewModel.Name;
person.Age = viewModel.Age;
// Save the changes to the database
return RedirectToAction("Details", new { id = person.Id });
}
// If there are validation errors, redisplay the edit form
return View(viewModel);
}
By retrieving the original model from a trusted source, you ensure that only the intended properties are modified.
Implementing these techniques collectively helps to prevent unintended updates by validating user input, restricting the properties that can be updated, and retrieving the original model from a trusted source.
Posted on July 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.