UpdateModel and TryUpdateModel in ASP.NET MVC

UpdateModel and TryUpdateModel in ASP.NET MVC

In this article, I am going to discuss two important functions i.e. UpdateModel and TryUpdateModel in ASP.NET MVC. We will also discuss the differences between them?

We will work with the same example that we started in our previous articles. So please read the following articles before proceeding to this article.

Business Object as Model in MVC.

FormCollection in MVC.

Model Binding in MVC.

In 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();
}
The above method can be rewritten 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” controller action method based on “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();
}
Please Note:

We have changed the names of “Create” action methods to “Create_Get” and “Create_Post” depending on the actions they respond to.

“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 “Create_Get()” controller action method is invoked. On the other hand, if a “POST” request is made to the same URL then “Create_Post()” controller action method is invoked.

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

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

Now let’s use TryUpdateModel() instead of UpdateModel(). Make changes to “Create_Post()” controller action method in “EmployeeController” as shown below.

[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();
    }
}

So 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)
{
    EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
    if (ModelState.IsValid)
    {
        employeeBusinessLayer.AddEmmployee(employee);
        return RedirectToAction("Index");
    }
    else
    {
        return View();
    }
}
So the next question is why do we need to explicitly invoke model binding?

If we 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 will discuss how to Edit a Model in ASP.NET MVC application.

SUMMARY

In this article, I try to explain UpdateModel and TruUpdateModel in ASP.NET MVC application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *