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.
Step 3
Select "empty" template, check the MVC checkbox, and click OK.
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.
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".
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
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".
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".
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
Entity Framework gets added and the respective class gets generated under the Models folder.
Step 5
Right-click on the Controllers folder add a controller.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
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.
The complete code for Home Controller
Controller without UpdateModel
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcUpdateModelAndTryUpdateModel_Demo.Models;
-
- namespace MvcUpdateModelAndTryUpdateModel_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext=new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- [HttpGet]
- public ActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult Create(Employee employee)
- {
- if (ModelState.IsValid)
- {
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- return RedirectToAction("Index");
- }
- return View();
- }
- }
- }
Controller with UpdateModel
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcUpdateModelAndTryUpdateModel_Demo.Models;
-
- namespace MvcUpdateModelAndTryUpdateModel_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext=new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- [HttpGet]
- [ActionName("Create")]
- public ActionResult Create_Get()
- {
- return View();
- }
-
- [HttpPost]
- [ActionName("Create")]
- public ActionResult Create_Post()
- {
- if (ModelState.IsValid)
- {
- var employee=new Employee();
- UpdateModel<Employee>(employee);
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- return RedirectToAction("Index");
- }
- return View();
- }
- }
- }
Controller with TryUpdateModel
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MvcUpdateModelAndTryUpdateModel_Demo.Models;
-
- namespace MvcUpdateModelAndTryUpdateModel_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext=new EmployeeContext();
-
- public ActionResult Index()
- {
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- [HttpGet]
- [ActionName("Create")]
- public ActionResult Create_Get()
- {
- return View();
- }
-
- [HttpPost]
- [ActionName("Create")]
- public ActionResult Create_Post()
- {
- var employee=new Employee();
- TryUpdateModel(employee);
-
- if (ModelState.IsValid)
- {
- _dbContext.Employees.Add(employee);
- _dbContext.SaveChanges();
- return RedirectToAction("Index");
- }
- return View();
- }
- }
- }
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.
Code for Index View
- @model IEnumerable<MvcUpdateModelAndTryUpdateModel_Demo.Models.Employee>
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>List of Employee</h2>
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>@Html.DisplayNameFor(m=>m.Name)</th>
- <th>@Html.DisplayNameFor(m=>m.Gender)</th>
- <th>@Html.DisplayNameFor(m=>m.PhoneNumber)</th>
- <th>@Html.DisplayNameFor(m=>m.Email)</th>
- <th>@Html.DisplayNameFor(m=>m.Designation)</th>
- <th>@Html.DisplayNameFor(m=>m.Salary)</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var employee in Model)
- {
- <tr>
- <td>@employee.Name</td>
- <td>@employee.Gender</td>
- <td>@employee.PhoneNumber</td>
- <td>@employee.Email</td>
- <td>@employee.Designation</td>
- <td>@employee.Salary</td>
- </tr>
- }
- </tbody>
- </table>
Code for Create View
- @model MvcUpdateModelAndTryUpdateModel_Demo.Models.Employee
- @{
- ViewBag.Title = "Create";
- }
-
- <h2>Create New Employee</h2>
- @using (Html.BeginForm())
- {
- <div class="form-group">
- @Html.LabelFor(m=>m.Name)
- @Html.TextBoxFor(m=>m.Name,new {@class="form-control"})
- @Html.ValidationMessageFor(m=>m.Name)
- </div>
- <div class="form-group">
- @Html.LabelFor(m=>m.Gender)
- @Html.DropDownList("Gender",new List<SelectListItem>
- {
- new SelectListItem { Text = "Male",Value = "Male"},
- new SelectListItem { Text = "Female",Value = "Female"}
- },"Choose Gender",new {@class="form-control"})
- @Html.ValidationMessageFor(m=>m.Gender)
- </div>
- <div class="form-group">
- @Html.LabelFor(m=>m.PhoneNumber)
- @Html.TextBoxFor(m=>m.PhoneNumber,new {@class="form-control"})
- @Html.ValidationMessageFor(m=>m.PhoneNumber)
- </div>
- <div class="form-group">
- @Html.LabelFor(m=>m.Email)
- @Html.TextBoxFor(m=>m.Email,new {@class="form-control"})
- @Html.ValidationMessageFor(m=>m.Email)
- </div>
- <div class="form-group">
- @Html.LabelFor(m=>m.Designation)
- @Html.TextBoxFor(m=>m.Designation,new {@class="form-control"})
- @Html.ValidationMessageFor(m=>m.Designation)
- </div>
- <div class="form-group">
- @Html.LabelFor(m=>m.Salary)
- @Html.TextBoxFor(m=>m.Salary,new {@class="form-control"})
- @Html.ValidationMessageFor(m=>m.Salary)
- </div>
- <div class="form-group">
- <button type="submit" class="btn btn-primary">Submit</button>
- </div>
- }
Step 7
Build and run the project by pressing Ctrl+F5.