Sunday 31 January 2021

Part 16: Model binding and exchanging data between view and model

#10 minutes of reading

 

In this article, I will explain model binding concept of MVC, frequently used concept while passing data from view to controller. I have provided link for MVC 5 article, as most of the concept of MVC 5 from old framework and MVC in Core framework are same. 

 

Create Asp.Net core 3.1 project using MVC template and add Employee model class in Models folder.


Add controller with name Employee and add create action method with name shown below. 


 Right click on create action and add view and click on Razor with below highlighted options.


Create view rendered with the help of MVC scaffolding. 


Run application and check on browser window.


Highlighted is create view from browser but when you put some data and click on create button nothing will happen, because we created Create action method in Employee controller for displaying Create view shown above, but not handled or created any action to handled post request. To complete post request from above view to server , create one more action method with [HTTPPost] attribute.

 


Run application, type below highlighted controller and action name (Employee/Create) and observe employee property showing for Post Create action method.

You can write property names directly from Employee model as parameter to create action method shown below.

 


It is recommended to use Post action([HttpPost]) instead of Get action while passing data (saving data to database) from view. Let’s check what is the issue with Get request. I have modified below Create action methods to produce below scenario.

Run application enter below URL highlighted, click inside URL textbox and press enter, make sure you do not press create button. Click inside URL after entering URL and press enter. This time request will go to HttpGet of Create action method and notice its shows EmployeId highlighted below. If you use Get method to store data, hackers get benefit to crack your application. Always use Post action to pass data from view to browser.

 


  

Please visit my MVC 5 bog for passing data from controller to View using ViewData, ViewBag and TempData from here. Most of MVC concept are same in old and new .Net framework.


Previous                                                                                                                                                Next

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home