Model Binding UpdateModel TryupdateModel

In this article we will understand model binding updateModel tryupdateModel -mvc ASP.NET MVC By Sagar Jaybhay.





But for this you need to read previous article where we start CRUD Operation in MVC.





Model Binding





[HttpPost]
public ActionResult Create(string EmpName, string EmpSalary, string gender, string EmpEmail, string EmpCity, int departmentid )

var employee = new Employee()

EmpName= EmpName,
EmpSalary=Convert.ToDouble(EmpSalary),
EmpCity= EmpCity,
EmpEmail= EmpEmail,
EmpGender=gender,
DepartmentID=departmentid


;


new BusinessLogic.Business().CreateEmployee(employee);
return RedirectToAction("DisplayCompleteEmployee");









In this above method, we use the method parameter and when we click on Create button this method is called. Also, we can use FormCollection in this which required the key to access data and we get this key from formcollectionobject.allkeys get all keys.





But how the form textboxes are bind correct data to parameters in that method is by using ModelBinder in MVC. In this, we required parameter names are mostly similar to textbox names so no need to explicitly written model binder but if our parameters name are different from FormCollection names then we write explicitly. If my textbox or form control name is the same as my parameter then there is no need for model binder MVC automatically do that for you.





Also, one more thing here order of parameter is not mattered but we have 20 to 30 parameters so it not good practice to write all these names in parameter list so there is the way how to do that.





UpdateModel In Asp.Net MVC









Suppose we don’t want to pass any parameter or object to the method but try to get all parameters from that submission form how we do that. For this, we need to use the UpdateModel function provided by the MVC framework.





[HttpPost]
public ActionResult Create()

Employee employee = new Employee();

if (ModelState.IsValid)

UpdateModel(employee);

new BusinessLogic.Business().CreateEmployee(employee);
return RedirectToAction("DisplayCompleteEmployee");

return View();









By using the above method we will do this but our program will not compile why, because we already have Create method which is decorated by HttpGet and MVC will throw compile-time error because here overloading is not present.






Severity

Code

Description

Project

File

Line

Suppression State

Error

CS0111

Type
'EmployeeController' already defines a member called 'Create' with the same
parameter types

MVCapp

D:\Target
Dec-2019\MVC
Learn\MVCStepByStep\WebApplication1\Controllers\EmployeeController.cs

80

Active








This is our error. To overcome this error we need to decorate our method with ActionName attribute and need to change the method name then our method becomes like below.





[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()

Employee employee = new Employee();

if (ModelState.IsValid)

UpdateModel(employee);

new BusinessLogic.Business().CreateEmployee(employee);
return RedirectToAction("DisplayCompleteEmployee");

return View();





By using this code our program will run and work as expected.





A key takeaway from this is mentioned below.





  1. ActionName:- this is decorater used for rename the method.
  2. UpdateModel:-  When we don’t want to pass parameter or strongly typed object to the method but want’s parameter should bind correctly then need to use UpdateModel method which binds all form parameters to a blank object which we created the syntax is below.




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




ModelState.IsValid:- this is an inbuilt method that returns the Boolean flag and it checks whether the model is valid or not if the model contains error it will return false.





What is the difference between UpdateModel and TryUpdateModel method in Asp.Net MVC?





First, we change our code a little bit, we make our model class which our case is Employee. Mark field with Required attribute means we want values for that property blank or null not allowed.





public class Employee

[DisplayName("ID")]
public int EmpID get; set;
[Required]
[DisplayName("Name")]
public string EmpName get; set;
[Required]
[DisplayName("Salary")]
public double EmpSalary get; set;
[Required]
[DisplayName("Gender")]
public string EmpGender get; set;
[DisplayName("City")]
[Required]
public string EmpCity get; set;
[Required]
[DisplayName("Email")]
public string EmpEmail get; set;
[Required]
public int DepartmentID get; set;






After that, we change method little bit





[HttpPost] // using UpdateModel
[ActionName("Create")]
public ActionResult Create_Post()

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

if (ModelState.IsValid)



new BusinessLogic.Business().CreateEmployee(employee);
return RedirectToAction("DisplayCompleteEmployee");

return View();









UpdateModel in MVC
UpdateModel in MVC








UpdateModel Error In MVC
UpdateModel Error In MVC








The model of type
'WebApplication1.Models.Employee' could not be updated.





Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The model of type 'WebApplication1.Models.Employees' could not be updated.





 Line 97: { Line 98: Employee employee = new Employee(); Line 99: UpdateModel(employee); Line 100: Line 101: if (ModelState.IsValid) 





Source File: D:\Target Dec-2019\MVC Learn\MVCStepByStep\WebApplication1\Controllers\EmployeeController.cs    Line: 99





We use UpdateModel first and then use ModelState.IsValid method by doing this will throw an error so our program will throw the above exception. For generating the above except we are not passing any parameter.





Now we can use tryUpdateModel method code for this is below





[HttpPost] // using TryUpdateModel
[ActionName("Create")]
public ActionResult Create_Post()

Employee employee = new Employee();
TryUpdateModel(employee);

if (ModelState.IsValid)



new BusinessLogic.Business().CreateEmployee(employee);
return RedirectToAction("DisplayCompleteEmployee");

return View();









TryUpdateModel In MVC
TryUpdateModel In MVC




From above image you will able to see by using TryUpdateModel method
our controller action method will not throw an error and our page looks like
above.





TryUpdateModel is returning the Boolean flag whether it will able to UpdateModel or not so we no need to use ModelState.IsValid method for checking whether it is valid or not.





[HttpPost] // using TryUpdateModel
[ActionName("Create")]
public ActionResult Create_Post()

Employee employee = new Employee();

if (TryUpdateModel(employee))



new BusinessLogic.Business().CreateEmployee(employee);
return RedirectToAction("DisplayCompleteEmployee");

return View();









GitHub :- https://github.com/Sagar-Jaybhay/MVC5

Comments

Popular posts from this blog

How to Start a YouTube Channel Free - Complete Guide

How Angular know which module is the startup module?

How to Start a YouTube Channel Free - Complete Guide