Data Entry Form in Asp.Net MVC


In this article we discuss how to create simple data entry application in Asp.Net MVC. We have HttpGet and HttpPost methods to work with the forms in Asp.Net MVC.

Open Microsoft Visual Studio 2013 => Create Asp.Net MVC application.

First add simple C# class to work with Employee data as shown below.

 

namespace MvcApplication.Models

{

    public class Employee

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public double Salary { get; set; }

    }

}

Add Employee controller to Controllers folder as shown below.

using MvcApplication.Models;

using System.Web.Mvc;

 

namespace MvcApplication.Controllers

{

    public class EmployeeController : Controller

    {

        //

        // GET: /Employee/

        [HttpGet]

        public ActionResult Index()

        {

            return View();

        }    

    }

}

 

Now right click on ActionResult method Index() in Controller and add Strongly typed view as shown below.

Add UI controls to view by using HTML helper classes as shown below. As you see this view binds to Employee model class.

@model MvcApplication.Models.Employee

 

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

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

    <title>Index</title>

</head>

<body>

    <div>

        @using (Html.BeginForm())

        {

 

            <p>Employee Id: @Html.TextBoxFor(obj => obj.Id) </p>

            <p>Name: @Html.TextBoxFor(obj => obj.Name) </p>

            <p>Salary: @Html.TextBoxFor(obj => obj.Salary) </p>

            <input type ="submit" value="Submit" />

        }

    </div>

</body>

</html>

 

Let’s add HttpPost method to controller to save the data from UI to database as shown below.

using MvcApplication.Models;

using System.Web.Mvc;

 

namespace MvcApplication.Controllers

{

    public class EmployeeController : Controller

    {

        //

        // GET: /Employee/

        [HttpGet]

        public ActionResult Index()

        {

            return View();

        }

 

        [HttpPost]

        public ActionResult Index(Employee obj)

        {

            int id = obj.Id;

            string Name = obj.Name;

            double salary = obj.Salary;

 

            //Call database by passing Id, Name, salary and save the data

            return View();        }

 

    }

}

 

As shown above HttpPost Index() method takes Employee object as input parameter. So this object contains the data entered by user. Here call the database to save the data entered by user.