3. How to Create ASP.NET MVC Application
3. How to Create ASP.NET MVC Application
html
Step 1
Now let us start with a step-by-step approach from the creation of simple MVC application as in the
following:
App_Start folder
This folder contains the application configuration details such as routing, authentication, filtering
of URL and so on.
Controller
This folder contains the controller and their methods. The controller is responsible for processing
the user request and return output as a view.
Models
This folder contains the entities or properties used to store the input values.
View
This folder contains the UI pages including shared page, .CSHTMl, .VBHTML, HTML,aspx pages that
show the output to the end user.
I hope you have understood folder structure in brief.
Step 2
Now let us delete all the existing views, models and controller folder files. We will create it again step-
by-step so that it is easier for us to understand. After deleting the existing files the Solution Explorer
will look as in the following:
Step 3
Now to create the Model.
Add the new class by right-clicking on the Model folder and provide the name as EmpModel:
Now declare the properties in the EmpModel class with a DataAnnotations attribute to validate the
values assigned to the properties. It is the same as get and set properties as we used in normal
applications. After declaring the properties the EmpModel class will look as in the following.
EmpModel.cs
using System.ComponentModel.DataAnnotations;
namespace InsertingDataintoDatabaseUsingMVC.Models
{
public class EmpModel
{
[Display(Name="First Name")]
[Required (ErrorMessage="First Name is required.")]
public string FName
{
get;
set;
}
[Display(Name = "Middle Name")]
public string MName
{
get; set;
}
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Last Name is required.")]
public string LName
{
get; set;
}
The attributes you have seen on each property is included in the namespace
System.ComponentModel.DataAnnotations that validates the input values at the client side as well as
the server side at the same time time as using the jQuery library files. We will learn it in detail in my
next article. I hope you have understood the concept of model.
Step 4
Now to create the Controller.
To create the controller, right-click on the Controller folder and click on Add new controller. It shows
the following window, provide a name for the controller with the suffix controller and then choose
empty MVC controller from templates as in the following screenshot:
After clicking on the Add button the following default code will be added into the controller class that
returns an empty view:
Now remove the preceding Index Action method from the preceding Empcontroller class and add the
following Action method named AddNewEmployee and the EmpModel reference:
return View();
}
}
Step 5
Now to add a View. Now that we have created the Controller, let us create the view for the
AddNewEmployee action method. Right-click near to the ActionResult method definition and click "Add
View...:".
1. Provide the view name in the free text area as shown in the following window. By default the
view is created with the name ActionResult method.
2. Choose one of the view engines from the given dropdownlist that are Razor or Aspx ,we have
selected the Razor view engine.
3. Check the checkBox to create a strongly-typed view.
4. Now choose the model class for a strongly-typed view from the given dropdownlist. In our
example we have choosen EmpModel that we created.
5. Choose the Scaffold template that will create an automated UI depending on the model class. In
our example we have chosen to create a template.
6. Check the References script libraries checkBox that will add jQuery libraries to validate the model
input values during execution.
7. Now check the user layout or master page layout checkBox that will add a shared page that
provides a consistent look across the applications.
8. Choose the view using the browse button of the following window. In our example we have
selected _Layout.cshtml.
9. Click on the Add button.
Now after clicking on the Add button it creates the following view with a rich UI design. The following
default code gets generated in the view:
@model InsertingDataintoDatabaseUsingMVC.Models.EmpModel
@{
ViewBag.Title = "Add Employee";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AddNewEmployee</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>EmpModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.FName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FName)
@Html.ValidationMessageFor(model => model.FName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MName)
@Html.ValidationMessageFor(model => model.MName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LName)
@Html.ValidationMessageFor(model => model.LName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.EmailId)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.EmailId)
@Html.ValidationMessageFor(model => model.EmailId)
</div>
<p>
<input type="submit" value="Save details" />
</p>
</fieldset>
}
@if (ViewBag.Message != null)
{
<span style="color:Green">@ViewBag.Message</span>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Now we have created the model, view and controller. After adding all these things the Solution
Explorer will look like the following:
Step 6
Now to configure the default routing. Run the application, then you will get the following error.
The preceding error occured because we did not configure the default routing specifying the page to
be shown by default after the user visits the application. To configure it find RouteConfig.cs under
App_Start folder:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "EMP", action = "AddNewEmployee", id = UrlParameter.Optional }
);
}
}
Step 7
Now run the application. On pressing F5 the following page will open and try to click on the Save
details button by entering invalid data; it shows the following error:
Now our model validated successfully depending on our set validation in the model class.
Step 8
Create the table in the database. To store the preceding form details in the database create the
following table:
Step 10
Configure the AddEmployee action method. To insert the data into the database write the following
code in the controller:
///<summary>
///Action method which
///insert the data into database by capturing
///Model values which comes from user as input
///</summary>
public ActionResult AddNewEmployee(EmpModel Emp)
{
//To Prevent firing validation error on first page Load
if (ModelState.IsValid)
{
connection();
SqlCommand com = new SqlCommand("InsertData", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@FName", Emp.FName);
com.Parameters.AddWithValue("@MName", Emp.MName);
com.Parameters.AddWithValue("@LName", Emp.LName);
com.Parameters.AddWithValue("@EmailId", Emp.EmailId);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
}
ModelState.Clear();
return View();
}
Now the complete code of Emp controller will look as in the following:
using System.Web.Mvc;
using InsertingDataintoDatabaseUsingMVC.Models;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace InsertingDataintoDatabaseUsingMVC.Controllers
{
public class EmpController : Controller
{
///<summary>
///Action method which
///insert the data into database by capturing
///Model values which comes from user as input
///</summary>
public ActionResult AddNewEmployee(EmpModel Emp)
{
//To Prevent firing validation error on first page Load
if (ModelState.IsValid)
{
connection();
SqlCommand com = new SqlCommand("InsertData", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@FName", Emp.FName);
com.Parameters.AddWithValue("@MName", Emp.MName);
com.Parameters.AddWithValue("@LName", Emp.LName);
com.Parameters.AddWithValue("@EmailId", Emp.EmailId);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
}
ModelState.Clear();
return View();
}
}
}
Step 11
Insert valid data and submit. Insert the valid data into the form and press the Save button then after
saving the details the following message will be shown:
Now from the preceding table records the record is inserted successfully.
Note:
Configure the database connection in the web.config file depending on your database server
location.
Since this is a demo, it might not be using proper standards so improve it depending on your
skills
This application is created completely focusing on beginners.