0% found this document useful (0 votes)
3 views

3. How to Create ASP.NET MVC Application

This document provides a step-by-step guide for beginners on how to create an ASP.NET MVC application that performs CRUD operations. It covers the creation of models, controllers, and views, as well as configuring routing and database interactions using stored procedures. The guide emphasizes understanding the folder structure and includes code examples for implementing the application functionality.

Uploaded by

Abdoulaye Diouf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

3. How to Create ASP.NET MVC Application

This document provides a step-by-step guide for beginners on how to create an ASP.NET MVC application that performs CRUD operations. It covers the creation of models, controllers, and views, as well as configuring routing and database interactions using stored procedures. The guide emphasizes understanding the folder structure and includes code examples for implementing the application functionality.

Uploaded by

Abdoulaye Diouf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Source :http://www.compilemode.com/2015/09/crud-operations-in-aspnet-mvc-5.

html

How to Create ASP.NET MVC Application


Filed Under: ASP.NET, MVC on 3 Sep 2015
There are many ways to insert data into a database using ASP.NET MVC, but in this example we use a
simple technique to insert data into a database using ASP.NET MVC. I have written this article focusing
on beginners so they can understand the basics of MVC. Please read my previous article using the
following link:

 ActionResult in ASP.NET MVC

Step 1
Now let us start with a step-by-step approach from the creation of simple MVC application as in the
following:

1. "Start" -> "All Programs" -> "Microsoft Visual Studio 2010".


2. "File" -> "New" -> "Project..." then select "C#" -> "ASP.NET MVC 4 Application" then choose
internet application.
3. Provide the website a name as you wish and specify the location.
4. Now after adding the MVC project, the Solution Explorer will look like the following:

Download Aspose : API To Create and Convert Files


After creating the ASP.NET MVC project, the preceding folder structure and files are added into the
project by default, so let us learn about them in brief 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;
}

[Display(Name = "Email Address")]


[DataType(DataType.EmailAddress,ErrorMessage="Invalid emaild address")]
[Required(ErrorMessage = "Emailld is required.")]
public string EmailId
{
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:

public class EmpController : Controller


{
//
// GET: /EMP1/
public ActionResult Index()
{
return 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:

public class EmpController : Controller


{
public ActionResult AddNewEmployee(EmpModel Emp)
{

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...:".

Then use the following procedure:

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:

Now write the following code in the RouteConfing.cs file:

public class RouteConfig


{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "EMP", action = "AddNewEmployee", id = UrlParameter.Optional }
);
}
}

In the preceding code in the defaults section:

 EMP: our controller name


 AddNewEmployee: our action (method) name
 Id: optional parameter for the action (method)

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:

I hope you have created the same table as above.


Step 9
Create a Stored Procedure. To insert the data into the table, create the following Stored Procedure.

Create Procedure InsertData


(
@FName varchar(50),
@MName varchar(50),
@LName varchar(50),
@EmailId varchar(50)
)
as begin

Insert into Employee (FName,MName,LName,EmailId ) values(@FName,@MName,@LName,@EmailId )


End

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)
{

ViewBag.Message = "New Employee Added Successfully";

}
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
{

private SqlConnection con;


private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
con = new SqlConnection(constr);

///<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)
{

ViewBag.Message = "New Employee Added Successfully";

}
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 let us confirm the details in the database table:

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.

You might also like