UpdateModel And TryUpdateModel In ASP.NET MVC

Introduction

This article will explain UpdateModel and TryUpdateModel in ASP.NET MVC. We will also discuss the differences between them.

What is the different between UpdateModel and TryUpdateModel?

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

Let us see them in action via a demo application. 

Step 1

Open Visual Studio 2015 or an editor of your choice and create a new project.

Step 2

Choose the "web application" project and give an appropriate name for your project.
 
UpdateModel And TryUpdateModel In ASP.NET MVC

Step 3

Select "empty" template, check the MVC checkbox, and click OK.
 
UpdateModel And TryUpdateModel In ASP.NET MVC

Step 4

Right-click the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
 
UpdateModel And TryUpdateModel In ASP.NET MVC

You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model. Give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".

UpdateModel And TryUpdateModel In ASP.NET MVC

After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".

UpdateModel And TryUpdateModel In ASP.NET MVC

After clicking on "Next", a window will appear. Choose New Connection. Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".

UpdateModel And TryUpdateModel In ASP.NET MVC

The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next".

UpdateModel And TryUpdateModel In ASP.NET MVC

After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".

UpdateModel And TryUpdateModel In ASP.NET MVC

Entity Framework gets added and the respective class gets generated under the Models folder.

UpdateModel And TryUpdateModel In ASP.NET MVC

Step 5

Right-click on the Controllers folder add a controller.
 
UpdateModel And TryUpdateModel In ASP.NET MVC

A window will appear. Choose MVC5 Controller-Empty and click "Add".

UpdateModel And TryUpdateModel In ASP.NET MVC

After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home.

UpdateModel And TryUpdateModel In ASP.NET MVC

The complete code for Home Controller

Controller without UpdateModel

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcUpdateModelAndTryUpdateModel_Demo.Models;  
  7.    
  8. namespace MvcUpdateModelAndTryUpdateModel_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext=new EmployeeContext();  
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             return View(employee);  
  18.         }  
  19.    
  20.         [HttpGet]  
  21.         public ActionResult Create()  
  22.         {  
  23.             return View();  
  24.         }  
  25.    
  26.         [HttpPost]  
  27.         public ActionResult Create(Employee employee)  
  28.         {  
  29.             if (ModelState.IsValid)  
  30.             {  
  31.                 _dbContext.Employees.Add(employee);  
  32.                 _dbContext.SaveChanges();  
  33.                 return RedirectToAction("Index");  
  34.             }  
  35.             return View();  
  36.         }  
  37.     }  
  38. }  

Controller with UpdateModel

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcUpdateModelAndTryUpdateModel_Demo.Models;  
  7.    
  8. namespace MvcUpdateModelAndTryUpdateModel_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext=new EmployeeContext();  
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             return View(employee);  
  18.         }  
  19.    
  20.         [HttpGet]  
  21.         [ActionName("Create")]  
  22.         public ActionResult Create_Get()  
  23.         {  
  24.             return View();  
  25.         }  
  26.    
  27.         [HttpPost]  
  28.         [ActionName("Create")]  
  29.         public ActionResult Create_Post()  
  30.         {  
  31.             if (ModelState.IsValid)  
  32.             {  
  33.                 var employee=new Employee();  
  34.                 UpdateModel<Employee>(employee);  
  35.                 _dbContext.Employees.Add(employee);  
  36.                 _dbContext.SaveChanges();  
  37.                 return RedirectToAction("Index");  
  38.             }  
  39.             return View();  
  40.         }  
  41.     }  
  42. }  

Controller with TryUpdateModel

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using MvcUpdateModelAndTryUpdateModel_Demo.Models;  
  7.    
  8. namespace MvcUpdateModelAndTryUpdateModel_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         private readonly EmployeeContext _dbContext=new EmployeeContext();  
  13.    
  14.         public ActionResult Index()  
  15.         {  
  16.             var employee = _dbContext.Employees.ToList();  
  17.             return View(employee);  
  18.         }  
  19.    
  20.         [HttpGet]  
  21.         [ActionName("Create")]  
  22.         public ActionResult Create_Get()  
  23.         {  
  24.             return View();  
  25.         }  
  26.    
  27.         [HttpPost]  
  28.         [ActionName("Create")]  
  29.         public ActionResult Create_Post()  
  30.         {  
  31.             var employee=new Employee();  
  32.             TryUpdateModel(employee);  
  33.    
  34.             if (ModelState.IsValid)  
  35.             {  
  36.                _dbContext.Employees.Add(employee);  
  37.                 _dbContext.SaveChanges();  
  38.                 return RedirectToAction("Index");  
  39.             }  
  40.             return View();  
  41.         }  
  42.     }  
  43. }  

Step 6

Right-click on Index method in HomeController. The "Add View" window will appear with default index name checked (use a Layout page), and click on "Add.
 
UpdateModel And TryUpdateModel In ASP.NET MVC

Code for Index View

  1. @model IEnumerable<MvcUpdateModelAndTryUpdateModel_Demo.Models.Employee>  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.    
  6. <h2>List of Employee</h2>  
  7. <table class="table table-bordered">  
  8.     <thead>  
  9.     <tr>  
  10.         <th>@Html.DisplayNameFor(m=>m.Name)</th>  
  11.         <th>@Html.DisplayNameFor(m=>m.Gender)</th>  
  12.         <th>@Html.DisplayNameFor(m=>m.PhoneNumber)</th>  
  13.         <th>@Html.DisplayNameFor(m=>m.Email)</th>  
  14.         <th>@Html.DisplayNameFor(m=>m.Designation)</th>  
  15.         <th>@Html.DisplayNameFor(m=>m.Salary)</th>  
  16.     </tr>  
  17.     </thead>  
  18.     <tbody>  
  19.     @foreach (var employee in Model)  
  20.     {  
  21.         <tr>  
  22.             <td>@employee.Name</td>  
  23.             <td>@employee.Gender</td>  
  24.             <td>@employee.PhoneNumber</td>  
  25.             <td>@employee.Email</td>  
  26.             <td>@employee.Designation</td>  
  27.             <td>@employee.Salary</td>  
  28.         </tr>  
  29.     }  
  30.     </tbody>  
  31. </table>  

Code for Create View

  1. @model MvcUpdateModelAndTryUpdateModel_Demo.Models.Employee  
  2. @{  
  3.     ViewBag.Title = "Create";  
  4. }  
  5.    
  6. <h2>Create New Employee</h2>  
  7. @using (Html.BeginForm())  
  8. {  
  9.     <div class="form-group">  
  10.         @Html.LabelFor(m=>m.Name)  
  11.         @Html.TextBoxFor(m=>m.Name,new {@class="form-control"})  
  12.         @Html.ValidationMessageFor(m=>m.Name)  
  13.     </div>  
  14.     <div class="form-group">  
  15.         @Html.LabelFor(m=>m.Gender)  
  16.        @Html.DropDownList("Gender",new List<SelectListItem>  
  17.        {  
  18.            new SelectListItem { Text = "Male",Value = "Male"},  
  19.            new SelectListItem { Text = "Female",Value = "Female"}  
  20.        },"Choose Gender",new {@class="form-control"})  
  21.         @Html.ValidationMessageFor(m=>m.Gender)  
  22.     </div>  
  23.     <div class="form-group">  
  24.         @Html.LabelFor(m=>m.PhoneNumber)  
  25.         @Html.TextBoxFor(m=>m.PhoneNumber,new {@class="form-control"})  
  26.         @Html.ValidationMessageFor(m=>m.PhoneNumber)  
  27.     </div>  
  28.     <div class="form-group">  
  29.         @Html.LabelFor(m=>m.Email)  
  30.         @Html.TextBoxFor(m=>m.Email,new {@class="form-control"})  
  31.         @Html.ValidationMessageFor(m=>m.Email)  
  32.     </div>  
  33.     <div class="form-group">  
  34.         @Html.LabelFor(m=>m.Designation)  
  35.         @Html.TextBoxFor(m=>m.Designation,new {@class="form-control"})  
  36.         @Html.ValidationMessageFor(m=>m.Designation)  
  37.     </div>  
  38.     <div class="form-group">  
  39.         @Html.LabelFor(m=>m.Salary)  
  40.         @Html.TextBoxFor(m=>m.Salary,new {@class="form-control"})  
  41.         @Html.ValidationMessageFor(m=>m.Salary)  
  42.     </div>  
  43.     <div class="form-group">  
  44.         <button type="submit" class="btn btn-primary">Submit</button>  
  45.     </div>  
  46. }  

Step 7

Build and run the project by pressing Ctrl+F5.
 
UpdateModel And TryUpdateModel In ASP.NET MVC


Similar Articles