We can get data from view to controller using many ways.
One of the way is using using request for getting data from view to controller.
Other way is to get data using viewmodel.
One of the way is using using request for getting data from view to controller.
Other way is to get data using viewmodel.
For best practice we should use view model to pass the data from view to controller.
Here I will show how can we get data using view model from view to controller.
For this we need to bind the fields of the view with the view model.
Example:
Lets pass data from controller to view using view model.
Name of the controller is HomeController.
Lets pass data from controller to view using view model.
Name of the controller is HomeController.
public ActionResult Index() { var myViewModel= new HomeViewModel(); // "HomeViewModel" viewmodel class created for HomeController myViewModel.EmpInfo = GetEmployeeInformation(); // "EmpInfo" is get,set method created in HomeViewModel //GetEmployeeInformation() is method which gets data of employee return View(myViewModel); }
The view Index.cshtml has fields employee first name & surname which is this
@model HomeViewModel @using (Html.BeginForm("Save", "Home", FormMethod.Post)) { @Html.EditorFor(model => @Model.EmpInfo.firstName) @Html.EditorFor(model => @Model.EmpInfo.surname) <input type="submit" value="Save"/> }
Here in view I have bonded fields firstName & surname with text boxes.
Now when we click on submit button it will go to Save action of the HomeController.
Now here we will pass the data which are written in textboxes to the fields firstName & surname using viewmodel.
The Action in controller is like
Now here we will pass the data which are written in textboxes to the fields firstName & surname using viewmodel.
The Action in controller is like
[HttpPost] public ActionResult Save(HomeViewModel homeModel) { <!-- Do your things here with data --> }
Here if we see in EmpInfo of homeModel there will be data in firstName & lastname.
The IMP thing is that we need to pass that viewmodel which we are using in View.
Here I was using HomeViewModel , that’s why I passed it to save method.
In short You just need to pass the viewmodel which is associated with the fields to the desired action which you are using to get the data from view to controller.
The IMP thing is that we need to pass that viewmodel which we are using in View.
Here I was using HomeViewModel , that’s why I passed it to save method.
In short You just need to pass the viewmodel which is associated with the fields to the desired action which you are using to get the data from view to controller.
No comments:
Post a Comment