UpdateModel and TryUpdateModel in ASP.NET MVC

UpdateModel and TryUpdateModel in ASP.NET MVC Application

In this article, I am going to discuss two important functions i.e. UpdateModel and TryUpdateModel in ASP.NET MVC Application. Please read our previous article before proceeding to this article as we are going to work with the same example. In our previous article, we discussed Model Binding in ASP.NET MVC Application. As part of this article, we are going to discuss the following pointers.

  1. Understanding the UpdateModel Function in ASP.NET MVC.
  2. Understanding the TryUpdateModel() in ASP.NET MVC.
  3. Difference between UpdateModel and TryUpdateModel function.
  4. Is it mandatory to use “UpdateModel()” or “Try”UpdateModel()” function to update the Model?
  5. Why do we need to explicitly invoke model binding?

In the Model Binding article, we discuss how to save the model data using the complex object as a parameter as shown below.

[HttpPost]
public ActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();

        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
    }
    return View();
}
UpdateModel and TryUpdateModel in ASP.NET MVC Application:

UpdateModel and TryUpdateModel in ASP.NET MVC Application

UpdateModel Function in ASP.NET MVC

Let us first understand how to use the UpdateModel function to capture the posted form data. In order to do this, please modify the Create (HttpPost) action method as shown below.

[HttpPost]
public ActionResult Create()
{
    if (ModelState.IsValid)
    {
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();

        Employee employee = new Employee();
        UpdateModel<Employee>(employee);

        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
    }
    return View();
}

When we make this change we get a compilation error stating – The.EmployeeController’ already defines a member called ‘Create’ with the same parameter types.

Our intention here is to overload the “Create” action method based on the “HttpGet” and “HttpPost“. To fix this error use the “ActionName” attribute as shown below.

[HttpGet]
[ActionName("Create")]
public ActionResult Create_Get()
{
    return View();
}

[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
    if (ModelState.IsValid)
    {
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();

        Employee employee = new Employee();
        UpdateModel<Employee>(employee);

        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
    }
    return View();
}
Understanding the code:

Here, first, we changed the names of the “Create” action methods to “Create_Get” and “Create_Post” depending on the actions they respond to.

The “ActionName” is specified as “Create” for both of these methods. So if a “GET” request is made to the “URL – http://localhost:54094/Employee/Create” then the “Create_Get()” action method is invoked. On the other hand, if a “POST” request is made to the same URL then the “Create_Post()” action method is invoked.

Instead of passing the “Employee” object as a parameter to the “Create_Post()” action method we are creating an instance of an “Employee” object within the function and updating it using the “UpdateModel()” function.

The “UpdateModel()” function inspects all the HttpRequest inputs such as Posted Form data, QueryString, Cookies, and Server variables and populates the employee object.

Understanding the TryUpdateModel() in ASP.NET MVC:

Now let’s understand how to use the TryUpdateModel function in ASP.NET MVC Application. Modify the create (HttpPost) action method as shown below. Here we use TryUpdateModel() instead of UpdateModel().

[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();

    Employee employee = new Employee();
    TryUpdateModel(employee);
    if (ModelState.IsValid)
    {
        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
    }
    else
    {
        return View();
    }
}

Now run the application and see everything is working as expected. Now let us understand the difference between them.

The difference is UpdateModel() throws an exception if validation fails whereas TryUpdateModel() will never throw an exception. The similarity is both the functions are used to update the Model with the Form values and perform the validations.

Is it mandatory to use “UpdateModel()” or “Try”UpdateModel()” function to update the Model?

The answer is NO. The above method can be re-written as shown below and we get the same behavior.

[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post(Employee employee)
{
    if (ModelState.IsValid)
    {
        EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
    }
    else
    {
        return View();
    }
}
Why do we need to explicitly invoke model binding?

If you want to limit what can be bound, explicitly invoking model binding can be very useful. We will discuss more this in a later session.

In our next article, I am going to discuss how to Edit a Model in ASP.NET MVC application. Here, in this article, I try to explain UpdateModel and TruUpdateModel in ASP.NET MVC application step by step with a simple example.