DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

Difference between updatemodel and tryupdatemodel with Example

In ASP.NET MVC, both UpdateModel and TryUpdateModel are used to update the model object with the values submitted from a form or user input. However, there is a crucial difference between them.

  1. UpdateModel: The UpdateModel method binds the incoming data to the model object and throws an exception if there are any model binding errors. This means that if there are validation errors or if the model properties cannot be successfully bound, it will result in an exception, potentially leading to an unhandled error.

Example of using UpdateModel:

public class PersonController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, FormCollection form)
    {
        var person = GetPersonById(id);

        // Update the model object with the form values using UpdateModel
        UpdateModel(person, form);

        // Perform any necessary operations (e.g., saving to the database)

        // Redirect to a different action or view
        return RedirectToAction("Details", new { id = person.Id });
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. TryUpdateModel: The TryUpdateModel method is an improvement over UpdateModel as it does not throw an exception in case of model binding errors. Instead, it returns a boolean value indicating whether the model binding was successful or not. If there are errors, you can handle them explicitly in your code without causing an unhandled exception.

Example of using TryUpdateModel:

public class PersonController : Controller
{
    [HttpPost]
    public ActionResult Edit(int id, FormCollection form)
    {
        var person = GetPersonById(id);

        // Try to update the model object with the form values
        if (TryUpdateModel(person, form))
        {
            // Model binding succeeded, perform any necessary operations (e.g., saving to the database)

            // Redirect to a different action or view
            return RedirectToAction("Details", new { id = person.Id });
        }
        else
        {
            // Model binding failed, handle the errors
            // You could show an error message or render the form view again with validation messages.
            // For example:
            ModelState.AddModelError("", "Error: Failed to update the person details.");
            return View("Edit", person);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, if the model binding using TryUpdateModel fails, we add a model-level error to the ModelState using ModelState.AddModelError, and then we return the "Edit" view, showing the form with the error message.

Using TryUpdateModel is generally considered safer than UpdateModel, as it helps prevent unhandled exceptions caused by model binding errors. Always prefer TryUpdateModel (or its asynchronous counterpart, TryUpdateModelAsync) over UpdateModel when updating models from user input.

Top comments (0)