In this article we will discuss about how to Pass (Get) data from View to Controller.
Here we discuss how to create Form Fields using Model class and then pass (get) data from View to Controller using Model class object in ASP.Net Core MVC 5.
Before start this article, please visit our previous article ASP.Net Core MVC-Display Message from Controller in View using JavaScript Alert MessageBox
Create an ASP.NET Core MVC Project
Let's create a ASP.NET Core MVC Project,
- Open Visual studio, create a New project
- Choose ASP.NET Core MVC template
- Then choose .NET Core 5 project
Model
We have created a Model of customer with followed below properties.
Controller
Then we have HomeController ( or you can create controller). There are two Action methods with the name Index, one for handling the GET operation while other for handling the POST operation.
The Action method for POST operation accepts an object of the Customer class as parameter. The values posted from the Form inside the View are received through this parameter.
View
- Next step is to add a View for the Controller and while adding will need to select the Customer class created earlier.
- Inside the View, in the top Customer class is declared as Model for the View.
- The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
- ActionName – Name of the Action. In this case the name is Index.
- ControllerName – Name of the Controller. In this case the name is Home.
- FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
There are four TextBox fields created for capturing values for Customer Id,Name, Address and Email are using the Html.TextBoxFor method. While for capturing the Gender value, a DropDownList with three options is created using the Html.DropDownListFor function.
There’s also a Submit Button at the end of the Form and when the Button is clicked, the Form is submitted
Run Application
When you run the application the form look like below and when we debug the files you can see all the customer details that we send from view it can find in controller action method like below.
And when click on submit button it post the data to HomeController POST method and you can see the customer information are came up to controller.
</> Find the Source Code in Github
Summary
Post a Comment