ASP.Net Core: Form Submit (Post) with Example

Introduction :

In this article I will explain with an example, how to submit Form (post) and send data from View to Controller in ASP.Net Core MVC,Here we will create Form Fields and then send data from View to Controller using model in ASP.Net Core MVC.

Step 1: Create Model class named : EmployeeModel.cs

Here we have used model to pass data from view to controller,the formcollection are also used for passing data to controller but in this tutorial we have used model.

EmployeesModel.cs:

    public class EmployeesModel
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
    }

Step 2: Create Home controller

The Home Controller consists of two Action methods with the name AddEmployee, one for handling the GET operation while other for handling the POST operation. The Action method for POST operation accepts the values of Model sent from the View.

        public IActionResult AddEmployee()
        {           
            return View();
        }

        [HttpPost]
        public IActionResult AddEmployee(EmployeesModel em)
        {     
            return View();
        }

Step 3:  Add View  named : AddEmploye.cshtml

The View consists of an HTML Form which has been created using the Razor Tag attributes with the following attributes.

asp-action – Name of the Action.
asp-for – specified the expression name

 

@model DotNetCoreRepository.Models.EmployeesModel@{
ViewData[“Title”] = “”;
}<h2>Add New Employee</h2><hr />
<div class=”row”>
<div class=”col-md-4″>
<form asp-action=”AddEmployee”>
<div asp-validation-summary=”ModelOnly” class=”text-danger”></div>
<div class=”form-group”>
<label asp-for=”UserName” class=”control-label”></label>
<input asp-for=”UserName” class=”form-control” />
</div>
<div class=”form-group”>
<label asp-for=”City” class=”control-label”></label>
<input asp-for=”City” class=”form-control” />
</div><div class=”form-group”>
<input type=”submit” value=”Create” class=”btn btn-primary” />
</div>
</form>
</div>
</div>

There are two TextBox fields created for capturing values for User name and City. Both TextBoxes have been specified with Name attribute which will be required to fetch the TextBox values inside the Controller. When you click on submit button the form will post data to controller using model.

Screenshot 1:

 ASP.Net Core: Form Submit (Post) with Example

Screenshot 2:  Asp.net core post form example

.Net Core Form Submit with Example

Summary :

In this article we have used model for passing data from view to controller, how to submit Form (post) and send data from View to Controller in ASP.Net Core MVC, Here we have create Form Fields and then send data from View to Controller.

 

Also Learn More Tutorial :

5 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *