Posting Data From View To Controller

Posting Data From View To Controller (Beta)

Here we are going to learn that how to post data from view to controller or ways of submitting html form in mvc. We already created the mvc application and added model, view and controller. If you are new then I recommended that first go through previous tutorials Start working with the first mvc application.

In asp.net web forms, just click the button and generate the event and in that event, retrieve all the textbox text, but in mvc there is not button click event available because mvc is not supporting server-side controls. So the question is how to achieve that button event logic for getting textbox values? In mvc we are using traditional form get and post logic. There are different ways to submit the html form in mvc. One by one I am going to explain all the possible ways.

1. Post the form by using model with strongly typed controls

In this process, first, we have to create a model class DemoModel that contains the properties. After that we will write the strongly types controls on view by using the razor. When we submit the form then it will pass the complete model class as a parameter in controller action method that defined with post attribute.

Model Code - Here are the model class codes that is used for generating strongly typed controls on view.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace FirstMvcApp.Models

{

    public class DemoModel

    {

        public string Name { get; set ; }

        public string EmailId { get; set ; }

        public string Mobile { get; set ; }

    }

}

View Code - Here are the view razor codes that will generate the html. Whenever you are creating strongly typed then you have to define the path of that model class on the page using @model keyword.

Html.BeginForm() have may overloaded methods. If you did not define the controller and action method then by default data will be posted on same action method which is defined with post attribute. Make sure you defined a button of type submit inside the form. Submit button used to submit the form in controller side.

<!DOCTYPE html>

@model< span class="Apple-converted-space">  FirstMvcApp.Models.< span style="font-size: 9.5pt; font-family: Consolas; color: rgb(43, 145, 175); background: white;">DemoModel< o:p>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="~/Content/bootstrap.css" rel="stylesheet" />

</head>

<body>

    <div>

        @using (Html.BeginForm())

        {

            <div class="form-group">

                <label>Name</label>

                @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })

            </div>

 

            <div class="form-group">

                <label>Email Id</label>

                @Html.TextBoxFor(m => m.EmailId, new { @class = "form-control" })

            </div>

 

            <div class="form-group">

                <label>Mobile</label>

                @Html.TextBoxFor(m => m.Mobile, new { @class = "form-control" })

            </div>

 

            <button type="submit" class ="btn btn-primary"> Save</button>

        }

    </div>

</body>

</html>

Controller Code - Here are the controller codes that will communicate with user requests. In below DemoController, we defined two action methods with same name, First Index method used to render the index view page. Second Index method with post attribute [HttpPost] is used for retrieving post data from index view. By default, all the method is type of get, so no need of defining [HttpGet], but for post you have to define the post attribute.

using System.Web.Mvc;

using FirstMvcApp.Models;

 

namespace FirstMvcApp.Controllers

{

    public class DemoController : Controller

    {

        // GET: Demo

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Index(DemoModel model)

        {

            // Implement your logics

            return View();

        }

    }

}

Output

demoimage

2. Post the form by parameters

In this process, we are posting the form's data without using any model class. In controller's post action method, we have to define the parameters that name are exactly same as html control name.

Controller Code - Here are the controller codes that will communicate with users. In below DemoController, we defined two action methods with same name, First Index method used to render the index view page. Second Index method with post attribute and parameters is used for retrieving post data from index view. Make sure that parameters name is same as html controls name.

using System.Web.Mvc;

using FirstMvcApp.Models;

 

namespace FirstMvcApp.Controllers

{

    public class DemoController : Controller

    {

        // GET: Demo

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Index(string txtName, string txtEmailId, string txtMobile)

        {

            // Implement your logics

            return View();

        }

    }

}

View Code - Here are the view html codes. If you want to pass textbox or any control data in to controller then that html name is defined in action method's parameter. Make sure that, the html control's name and parameter names are exactly same then only that control value retrieved in controller.

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="~/Content/bootstrap.css" rel="stylesheet" />

</head>

<body>

    <div>

        @using (Html.BeginForm())

        {

            <div class="form-group">

                <label>Name</label>

                <input type="text" class="form-control" name="txtName" placeholder="Name">

            </div>

 

            <div class="form-group">

                <label>Email Id</label>

                <input type="email" class="form-control" name="txtEmailId" placeholder ="Email Id">

            </div>

 

            <div class="form-group">

                <label>Mobile</label>

                <input type="number" class="form-control" name="txtMobile" placeholder="Mobile">

            </div>

 

            <button type="submit" class ="btn btn-primary"> Save</button>

        }

    </div>

</body>

</html>

Output

demoimage

3. Post the form by using FormCollection

In this process we will post the form and retrieve the form's elements value by FormCollection class. We have to just pass FormCollection class as parameter in post action method and then retrieve the elements value by specifying their name.

Controller Code - In this process we are sending complete form data in one parameter. Advantage of this process over first one (send by parameters) is that, if you have lots of controls on page then its difficult to specify all the control in parameters. So in that situation you can pass complete form in one parameter. You can retrieve the individual control by defining the string name of control. Below codes are showing the way of retrieving the each control value.

using System;

using System.Web.Mvc;

using FirstMvcApp.Models;

using System.Collections.Generic;

 

namespace FirstMvcApp.Controllers

{

    public class DemoController : Controller

    {

        // GET: Demo

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Index(FormCollection form)

        {

            // Implement your logics

            string name = form["txtName"];

            string emailId = form["txtEmailId"];

            string mobile = form["txtMobile"];

            return View();

        }       

    }

}

View Code - Here is view html codes.

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="~/Content/bootstrap.css" rel="stylesheet" />

</head>

<body>

    <div>

        @using (Html.BeginForm())

        {

            <div class="form-group">

                <label>Name</label>

                <input type="text" class="form-control" name="txtName" placeholder="Name">

            </div>

 

            <div class="form-group">

                <label>Email Id</label>

                <input type="email" class="form-control" name="txtEmailId" placeholder ="Email Id">

            </div>

 

            <div class="form-group">

                <label>Mobile</label>

                <input type="number" class="form-control" name="txtMobile" placeholder="Mobile">

            </div>

 

            <button type="submit" class ="btn btn-primary"> Save</button>

        }

    </div>

</body>

</html>

Output:

demoimage

4. Post the form by Request.Form Collection

In this process, we are posting the form's data without any model class and without parameters. The Request.Form collection retrieves the values of form elements that posted to http request using post method. You can retrieve the form element value by their name or integer index value.

View Code - Here is the view html codes. Here we used overloaded method of Html.BeginForm(). First parameter is representing action name and second parameter is representing controller name.

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="~/Content/bootstrap.css" rel="stylesheet" />

</head>

<body>

    <div>

        @using (Html.BeginForm("SubmitData", "Demo"))

        {

            <div class="form-group">

                <label>Name</label>

                <input type="text" class="form-control" name="txtName" placeholder="Name">

            </div>

 

            <div class="form-group">

                <label>Email Id</label>

                <input type="email" class="form-control" name="txtEmailId" placeholder ="Email Id">

            </div>

 

            <div class="form-group">

                <label>Mobile</label>

                <input type="number" class="form-control" name="txtMobile" placeholder="Mobile">

            </div>

 

            <button type="submit" class ="btn btn-primary"> Save</button>

        }

    </div>

</body>

</html>

Controller Code - Here is the controller code that will communicate with user actions. First Index method used to render the index view page. Second SubmitData method with post attribute is used for retrieving post data from index view. In post action method we did not defined any parameters. Here we are retreiving by request class. You have to define string html name in Request.Form.

using System;

using System.Web.Mvc;

using FirstMvcApp.Models;

 

namespace FirstMvcApp.Controllers

{

    public class DemoController : Controller

    {

        // GET: Demo

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult SubmitData()

        {

            // Implement your logics

            string name = Request.Form["txtName"];

            string emailId = Request.Form["txtEmailId"];

            string mobile = Request.Form["txtMobile"];

 

            return RedirectToAction("Index");

        }

    }

}

Here we defined different- different method name for get and post method, because we cannot defined two methods with same name. We can only defined overloaded methods that we defined in above.

Output:

demoimage