In this article I will explain with an example, how to pass (send) data from one cshtml page (View) to another in ASP.Net MVC Razor.
The data from the Source cshtml page (View) will be posted (submitted) using Form Post to the Controller’s Action method of the Destination cshtml page (View).
Then finally, the received data will be displayed in the Destination cshtml page (View) using ViewBag.
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method handles the call made from the POST function from the Source View and it returns the received data to the Destination View using ViewBag object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Greetings(string name)
{
ViewBag.Name = name;
return View();
}
}
Source cshtml page
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 Greetings.
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.
The Form consists of a TextBox and a Submit Button.
When the Submit Button is clicked, the Form gets submitted and the TextBox value is sent to the Controller’s Action method of the Destination View.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Greetings", "Home", FormMethod.Post))
{
<table cellpadding="2" cellspacing="0" border="0">
<tr>
<td>Name:</td>
<td>
@Html.TextBox("Name")
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
}
</body>
</html>
Destination cshtml page
Inside this View, the data from the ViewBag object is displayed using Razor syntax.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Greetings</title>
</head>
<body>
<span>Name: </span>@ViewBag.Name
</body>
</html>
Screenshot
Downloads