In this article I will explain with an example, how to pass (send) TextBox values from View to Controller in ASP.Net Core MVC.
This article will illustrate how to send TextBox values using Form Collection in ASP.Net Core MVC.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Controller
The Controller consists of 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 the values of First Name and Last Name sent from the View and it is assigned to a ViewBag object.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(string firstName, string lastName)
    {
        ViewBag.Name = string.Format("Name: {0} {1}", firstName, lastName);
        return View();
    }
}
 
 
View
The View consists of an HTML Form which has been created using the Razor Tag attributes with the following attributes.
asp-actionName of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
There are two TextBox fields created for capturing values for First Name and Last Name. Both TextBoxes have been specified with Name attribute which will be required to fetch the TextBox values inside the Controller.
There’s also a Submit Button at the end of the Form and when the Button is clicked, the Form is submitted.
Finally, the values of the ViewBag object is displayed using Razor syntax.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
        <table>
            <tr>
                <td>First Name: </td>
                <td><input type="text" id="txtFirstName" name="FirstName"/></td>
            </tr>
            <tr>
                <td>Last Name: </td>
                <td><input type="text" id="txtLastName" name="LastName"/></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
            </tr>
        </table>
        <hr/>
        @ViewBag.Name
    </form>
</body>
</html>
 
 
Screenshot
ASP.Net Core: Pass (Send) TextBox values from View to Controller
 
 
Downloads