In this article we are going to discuss about form data submission using @Html.BeginForm Helper method and passing the data to another view.
In this article we are using Tempdata for passing data between different controllers.
The main advantage of TempData is passing data between different controllers when redirect happens it retains data between controller to controller.
Firstly, we are going to create the MVC Solution
Select Empty Template and add MVC folder reference,
Add new Controller in Controllers folder,
Select MVC 5 Controller - Empty,
Give Conroller name as Home,
Add a View
Right click on the Action Name and add view,
Create Model class in Model folder,
- public class Employee
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- public string Salary
- {
- get;
- set;
- }
-
- }
Controller Code - using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Model_Binding_in_Diffrent_Ways.Models;
- namespace Model_Binding_in_Diffrent_Ways.Controllers
- {
- public class HomeController: Controller
- {
-
- public ActionResult Index()
- {
- Employee emp = new Employee();
- return View(emp);
- }
-
- [HttpPost]
- public ActionResult SubmitEmp(Employee emp)
- {
- TempData["Emp"] = emp;
- return Redirect("/Home/EmpDetails");
- }
-
- public ActionResult EmpDetails()
- {
- Employee emp = TempData["Emp"] as Employee;
- return View(emp);
- }
- }
- }
Index View Code - @model Model_Binding_in_Diffrent_Ways.Models.Employee
- @{
- ViewBag.Title = "Index";
- }
- @Html.BeginForm("SubmitEmp", "Home",FormMethod.Post)
- {
- <table class="table table-responsive table-bordered" >
- <tr>
- <td>First Name</td>
- <td>
- @Html.TextBox("FirstName" ,null,htmlAttributes: new { @class = "form-control" })
-
- </td>
- </tr>
- <tr>
- <td>Last Name</td>
- <td>
- @Html.TextBox("LastName", null, htmlAttributes: new { @class = "form-control" })
-
- </td>
- </tr>
- <tr>
- <td>Salary</td>
- <td>
- @Html.TextBox("Salary", null, htmlAttributes: new { @class = "form-control" })
-
- </td>
- </tr>
- <tr>
- <td colspan="2" align="right">
- <input type="submit" value="Submit" class="btn btn-success" />
- </td>
- </tr>
- </table>
- }
Run the application, provide the values and submit the form,
EmpDetails View - @model Model_Binding_in_Diffrent_Ways.Models.Employee
- @ {
- ViewBag.Title = "EmpDetails";
- }
-
- @if(Model != null) { < div >
- Employee Deatils < /div>
-
- < div >
- First Name: @Model.FirstName < /div>
-
- < div >
- Last Name: @Model.LastName < /div>
-
- < div >
- Salary: @Model.Salary < /div>
- } else { < div > Employee Deatils not found < /div>
- }
The Output of the EmpDetails View,