articles

Home / DeveloperSection / Articles / Creating Data Entry Application in ASP.NET MVC using Razor view engine

Creating Data Entry Application in ASP.NET MVC using Razor view engine

Anonymous User29172 09-Apr-2012

In this article I am going to explain that how to create a simple data entry application using mvc3 framework by using razor view engine. In this task you will learn how to create a model, apply initial level validation for model, rendering view and creating controller. You will also learn, how to use transfer records from controller to view using view bag object. After completing this task you will learn some key concepts like what is model binding and how it is different from view state concept in ASP.NET?

For completing this task I used visual studio 2010 and ASP.NET MVC3 framework with MVC3 updates. If you did not have MVC3 or MVC3 updates then you can download it from Microsoft site. For completing this task I used Pro. ASP.NET MVC3 Framework book of APRESS publication.

To create ASP.NET MVC3 web application you need to follow these steps

1)      Open visual studio followed by create new project then choose ASP.NET MVC3 application. When you choose ASP.NET MVC3 application then it looks like following

Creating Data Entry Application in ASP.NET MVC using Razor view engine

Here you need to provide your project name and location where you want to create project. After providing these details click on OK button.

2)      When you click on OK button then a Dialog box will appear where you specify that which type of MVC project you wants to create. One thing I want to clear that previous dialog box which you had seen is pop-up by visual studio but this pop-up dialog box is pop-up by ASP.NET MVC3 not by visual studio. The appearing dialog box look like following
Creating Data Entry Application in ASP.NET MVC using Razor view engine

Here in above screen shot you will see 4 options to create ASP.NET MVC3 application. Here you will see so many options as I had installed ASP.NET MVC3 toolkit updates and some extension updates provided by visual studio. Let me explain these options which are showing in above screen shot.

a)      Empty: You will choose Empty template when you want to create whole application by yourself. After choosing this option only required folder and structures are provided by visual studio.  For completing this task I am using this option.

b)      Internet Application: When you choose Internet Application template then a sample mvc application is provided to you. You can use this template for learning basics concepts.

c)       Intranet Application: When you want to implement domain level security, only then you can choose this template.

d)      Telerik MVC Web Application: You will see this option as I had installed telerik add-on. I am not going to describe this option as this one not come with ASP.NET MVC3 tool kit updates,

e)      View Engine: After selecting appropriate template you need to choose a view engine. Here you will find two type of View engine, 1) Razor view engine which is by default selected and other one is ASPX view engine. For completing this task I used razor view engine.

After selecting appropriate options click on OK button. For this exercise I had chosen Empty template with razor view engine.

Now after performing these steps out first job is to create a model. In MVC Model represents a class which is normally resides in /Model folder. In Model class we specify structure or behaviour or form. All required validation is implemented in Model which is also known as Model level validation. Here I am creating a model which have name Person. For creating Model, steps are described in below image.

Creating Data Entry Application in ASP.NET MVC using Razor view engine

Here you will see all steps in highlighted form. When you click on Class… option then a Model dialog box opens where you provide name of your model class.

Creating Data Entry Application in ASP.NET MVC using Razor view engine

Here you will see that I am creating a Model class which have name Person. Click on Add button to create this model class. When you click on Add button then code editor window of Person class is open where you have to write following code to create a Person model. Remember that in this model I am implementing validation also which is known as data annotation validation. For implementing data annotation validation you need to implement System.ComponentModel.DataAnotations namespace. You can copy and paste below code to implement this model.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
 
namespace DataEntryApplication.Models
{
    public class Person
    {
        [Required(ErrorMessage = "ID field is required.")]
        public string ID { get; set; }
 
        [Required(ErrorMessage = "Name field is required.")]
        public string Name { get; set; }
 
        [Required(ErrorMessage = "Email field is required.")]
        [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please enter a valid email address.")]
        public string Email { get; set; }
 
        [Required(ErrorMessage = "Please select your gender.")]
        public bool? Gender { get; set; }
 
        [Required(ErrorMessage = "Contact number field is required.")]
        public int ContactNumber { get; set; }
    }
}

 After creating Person model, you need to build your project because if you did not build it then it is not reflected in view.

Now our next step is to add a controller for our data entry application. In ASP.NET MVC controller is responsible for processing incoming request and rendering a particular view. Follow these steps to add a controller.


Creating Data Entry Application in ASP.NET MVC using Razor view engine

Here you will see that I am creating a controller named Home. You need to choose Empty controller from scaffolding options. After clicking on Add button a controller is added in your application. After creating controller create 2 action methods in your controller.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataEntryApplication.Models;
 
namespace DataEntryApplication.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        [HttpGet]
        public ActionResult DataEntryForm()
        {
            return View(); ///Return a DataEntryForm view.
        }
 
        [HttpPost]
        public ActionResult DataEntryForm(Person person)
        {
            if (ModelState.IsValid)
            {
                ///Here we check that if all entries are valid in form
                ///then we call Result view.
                return View("Result", person);
            }
            else
            {
                ///And if entries are not valid then we render that view again.
                return View();
            }
        }
 
    }
}

 After creating these two action methods, our next step is to add these two views whose name is DataEntryForm and Result, in our application. We can create two type views, one is loosely typed and other one is strongly typed view. Here I am going to create a strongly typed view. For creating strongly typed view, Right click on action method then followed by Add View menu option. 

Creating Data Entry Application in ASP.NET MVC using Razor view engine

Here I marked Add View by Red rectangle. When you click on Add View then Add View dialog box opens.

Creating Data Entry Application in ASP.NET MVC using Razor view engine

Here you will see that I am providing View Name as DataEntryForm, select Razor(CSHTML) as view engine and select Model class for creating strongly typed view. If class is not populated in Model class dropdown then you need to build it. After providing these information click on Add button and View is automatically created. Follow these steps to create Result view also.

 Write down following code in DataEntryForm view.

@model DataEntryApplication.Models.Person

@{
    ViewBag.Title = "DataEntryForm";
}
<div>
    <fieldset>
        <legend>Person Details Form</legend>
        @using (Html.BeginForm())
        { 
            <div>
                <div class="editor-label ">
                    @Html.LabelFor(per => per.ID)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(per => per.ID)
                    @Html.ValidationMessageFor(per => per.ID)
                </div>
            </div>
            <div>
                <div class="editor-label ">
                    @Html.LabelFor(per => per.Name)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(per => per.Name)
                    @Html.ValidationMessageFor(per => per.Name)
                </div>
            </div>
            <div>
                <div class="editor-label ">
                    @Html.LabelFor(per => per.Email)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(per => per.Email)
                    @Html.ValidationMessageFor(per => per.Email)
                </div>
            </div>
            <div>
                <div class="editor-label ">
                    @Html.LabelFor(per => per.Gender)
                </div>
                <div class="editor-field">
                    @Html.DropDownListFor(per => per.Gender, new[] {
                                new SelectListItem(){Text = "Male" , Value=bool.TrueString},
                                new SelectListItem(){Text ="Female" , Value = bool.FalseString},
                            }, "Select Your Gender")
                    @Html.ValidationMessageFor(per => per.Gender)
                </div>
            </div>
            <div>
                <div class="editor-label ">
                    @Html.LabelFor(per => per.ContactNumber)
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(per => per.ContactNumber)
                    @Html.ValidationMessageFor(per => per.ContactNumber)
                </div>
            </div>
            <p><input type = "submit" value="Submit Details" /></p>
        }
    </fieldset>
</div>

 And in Result View you need to write following code.

@model DataEntryApplication.Models.Person

 
@{
    ViewBag.Title = "Result";
}
 
<h2>Result</h2>
 
<fieldset>
    <legend>Person</legend>
 
    <div class="display-label">Name</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>
 
    <div class="display-label">Email</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Email)
    </div>
 
    <div class="display-label">Gender</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>
 
    <div class="display-label">ContactNumber</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.ContactNumber)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
    @Html.ActionLink("Back to List", "Index")
</p>

 After creating these two views you need to make a few changes in Global.asax file. Here you need to change router setting.

Write down or replace following code in global.asax file.


public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "DataEntryForm", id = UrlParameter.Optional } // Parameter defaults
            );
 
        }

 After making these changes you application is ready to execute. Execute you application and see the output.

Thanks for reading this article. Please write your valuable comments.



Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By