ASP Example
-
Upload
satya-surendra -
Category
Documents
-
view
218 -
download
0
Transcript of ASP Example
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 1/201ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
9,163,646 members and growing! Email Password Sign in Join Lost password?
Home Articles Quick Answers Discussions Zones Features Community Help! Search site
Article Browse Code Stats Revisions Alternatives
13
» Web Development » ASP.NET » Samples
Licence CPOLFirst Posted 23 Feb 2011
Views 17,343Downloads 931Bookmarked 33 times
ASP.NET ApplicationDevelopment Using MVCBy Abdul Quader Mamun | 23 Feb 2011 | Article
C# ASP.NET .NET Dev Beginner MVC EF
A sample ASP.NET application development using MVC.
See AlsoMore like this
More by this author
4.41 (8 votes)
Download source code - 1.37 MB
Overview
ASP.NET provides the MVC framework as an alternate to the ASP.NET Web Forms pattern
for developing web applications. MVC (Model-View-Controller) is a lightweight, highly
testable presentation framework that is integrated with the existing ASP.NET features such
as Master Pages and Membership-based authentication.
Introduction
The System.Web.Mvc namespace is for ASP.NET MVC. MVC is a standard Design Pattern.
MVC has the following components:
Controller
Classes that handle incoming requests to the application, retrieve model data, and
then specify view templates that return a response to the client.
Model
Classes that represent the data of the application and that use validation logic to
enforce business rules for that data.
View
Template files that your application uses to dynamically generate HTML responses.
Background
In this demonstration, I will design a database using SQL Server Management Studio 2005. I
will develop an ASP.NET MVC application and will describe all of its parts.
Let’s Get Started
Open SQL Management Studio 2005. Crate a database and name it Inventory . Design a
database table like below:
Hot News: Introducing Outlook.com- Modern Email for the Next BillionMailboxes
The Code Project Insider. Freeeach morning.
Related Articles
A Simple Tutorial on DevelopingASP.NET Applications in MVCPattern
Developing and Unit Testing anASP.NET MVC 2 Application
Developing Well-Designed ASP.NETMVC Applications with S#arp Lite
BDD using SpecFlow on ASP.NETMVC Application
Development of web applicationusing MVC II design pattern or why
following MVC II will help meEvent Calendar for an ASP.NETMVC Application
Implement secure ASP.NET MVCapplications
Developing Facebook ConnectApplication using ASP.NET
Using MVC to Unit Test WPFApplications
N-Tier development with ASP.NETMVC, WCF, and LINQ
Introduction to ASP.NET MVC 3
Creating a Bilingual ASP.NET MVC Application – Part I
Webpart/Portlet development inASP.NET MVC Framework
Routing a Localized ASP.NET MVCApplication
Creating a Bilingual ASP.NET MVC Application – Part 2
ASP.NET MVC Application in Action- I (DailyJournal)
How To Improve the Performanceof ASP.NET MVC Web Application
Actions in ASP.NET MVC 3
MVC Based ASP.NET Applicationwith Dependency Injection
MVC Bricks for ASP.net
×Sign up for our free weekly Web Developer Newsletter.
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 2/202ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 1
1. Open Microsoft Visual Studio 2010
2. Create a new project (File> New> Project> Visual C#): ASP.NET MVC 3 Web
Application
3. Named it ASPNETMVCApplication
4. Click on the OK button
Figure 2
1. Select a template for Internet Application2. View engine to Razor3. Create a unit test project to uncheck4. Click on the OK button
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 3/203ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 3
The default project will be created. Now Add Library Package Reference. We will use a
.NET Framework data-access technology known as the Entity Framework. The Entity
Framework (often referred to as “EF”) supports a development paradigm called code-first.
Code-first allows you to create model objects by writing simple classes. You can then have
the database created on the fly from your classes, which enables a very clean and rapid
development workflow.
We'll start by using the NuGet package manager (automatically installed by ASP.NET MVC 3)
to add the EFCodeFirst library to the ASPNETMVCApplication project. This library lets us use
the code-first approach. To add Entity Framework reference:
From the Tools menu, select Library Package Manager and then Add Library Package
Reference.
Figure 4
In the Add Library Package Reference window, click online.
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 4/204ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 5
Click the NuGet Official package source.
Figure 6
Find EFCodeFirst, c lick on install.
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 5/205ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 7
Click on I Accept. Entity Framework will install and will add a reference to the project.
Figure 8
Click on the Close button.
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 6/206ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 9
Adding a Model Class
1. Right click on Models from Solution Explorer2. Select Add3. Select Class
4. Name it Book.cs
Figure 10
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 7/207ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 11
Add the following properties in the Book.cs file:
Collapse | Copy Code
namespace ASPNETMVCApplication.Models
{
public class Book
{
public Int64 Id { get; set; }
public String Title { get; set; }
public String ISBN { get; set; }
public Decimal Price { get; set; }
}
}
Add another class the way you did for Book.cs and name it BookDBContext.cs. Add aSystem.Data.Entity namespace reference in the BookDBContext.cs file.
Collapse | Copy Code
using System.Data.Entity;
Add the following code in the BookDBContext class. And derive it from the DbContextclass so that all data operations can be handled by the Books property.
Note: The property name Books must be the same as the database table name Books.
Here is the complete code:
Collapse | Copy Code
using System;
using System.Web;
using System.Data.Entity;
namespace ASPNETMVCApplication.Models
{
public class BookDBContext:DbContext
{
public DbSet<Book> Books { get; set; }
}
}
Add a connection string in the web.config file. Remember, the connection string name must
be the same as BookDBContext.
Collapse | Copy Code
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 8/208ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
<connectionStrings>
<add name="BookDBContext"
connectionString="data source=Home-PC;
uid=sa;pwd=1234;Initial Catalog=Inventory"
providerName="System.Data.SqlClient" />
</connectionStrings>
Adding the Controller
1. Right click on Controller from Solution Explorer2. Select Add
3. Select Controller4. Name it BookController
5. Add act ion methods for Create, Update, Delete, and Details scenarios to Checked
Figure 12
Figure 13
It will add the following code:
Collapse | Copy Code
namespace ASPNETMVCApplication.Controllers
{
public class BookController : Controller
{
//
// GET: /Book/
public ActionResult Index()
{
return View();
}
//
// GET: /Book/Details/5
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 9/209ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Book/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Book/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}}
//
// GET: /Book/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Book/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{ try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Book/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Book/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 10/2010ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Now add the following namespaces in the BookController.cs file:
Collapse | Copy Code
using System.Linq;
using ASPNETMVCApplication.Models;
Declare a global instance variable of the BookDBContext class in the BookControllerclass.
Collapse | Copy Code
BookDBContext _db = new BookDBContext();
Add the following code in the Index() method:
Collapse | Copy Code
public ActionResult Index()
{ var books = from book in _db.Books
select book;
return View(books.ToList());
}
This is the LINQ code for getting books and books.ToList() to display the book list in the
View.
Now right click on Solution and select Build to build the solution.
Adding the View
1. Right click in the Index method
2. Select View3. Create a strongly-typed view to Checked4. Select Model class to Book (ASPNETMVCApplication.Models)5. Scaffold template to List6. Click on the OK button
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 11/2011ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 14
It will add the Index.cshtml file.
Collapse | Copy Code
@model IEnumerable<ASPNETMVCApplication.Models.Book>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
Title
</th>
<th>
ISBN
</th>
<th>
Price
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
<td>
@item.Title
</td>
<td>
@item.ISBN
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 12/2012ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
</td>
<td>
@String.Format("{0:F}", item.Price)
</td>
</tr>
}
</table>
Now, add the Create View.
Adding the Create View
1. Right click on the Create method
2. Select View3. Create a strongly-typed view to Checked4. Select Model class to Book (ASPNETMVCApplication.Models)5. Scaffold template to Create6. Click on the OK button
It will add the Create.cshtml file.
Collapse | Copy Code
@model ASPNETMVCApplication.Models.Book
@{
ViewBag.Title = "Create";
}
<h2>Create</h2><script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script><script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Book</legend><div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">@Html.LabelFor(model => model.ISBN)
</div>
<div class="editor-field">
@Html.EditorFor(model =>
Now add the following code in the Create method in the BookController class.
Collapse | Copy Code
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
Book book = new Book();
if (ModelState.IsValid){
book.Title = collection["Title"].ToString();
book.ISBN = collection["ISBN"].ToString();
book.Price = Convert.ToDecimal(collection["Price"]);
_db.Books.Add(book);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View(book);
}
}
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 13/2013ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
catch
{
return View();
}
}
Now we will add the Edit View.
Adding the Edit View
1. Right click on the Edit method
2. Select View3. Create a strongly-typed view to Checked4. Select Model class to Book (ASPNETMVCApplication.Models)5. Scaffold template to Edit6. Click on the OK button
Figure 15
It will add the Edit.cshtml file:
Collapse | Copy Code
@model ASPNETMVCApplication.Models.Book
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2><script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script><script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Book</legend>@Html.HiddenFor(model => model.Id)
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 14/2014ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ISBN)
</div>
<div class="editor-field">
@Html.EditorFor(model =>
Now add the following code in the Edit method in the BookController class.
Collapse | Copy Code
public ActionResult Edit(int id)
{
Book book = _db.Books.Find(id);
if (book == null)
return RedirectToAction("Index");
return View(book);
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
var book = _db.Books.Find(id);
UpdateModel(book);
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
ModelState.AddModelError("", "Edit Failure, see inner exception");
return View();
}
}
Now we will add the Details View.
Adding the Details View
1. Right click on the Edit method
2. Select View3. Create a strongly-typed view to Checked4. Select Model class to Book (ASPNETMVCApplication.Models)5. Scaffold template to Details6. Click on the OK button
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 15/2015ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 16
It will add the Details.cshtml file:
Collapse | Copy Code
@model ASPNETMVCApplication.Models.Book
@{
ViewBag.Title = "Details";
}
<h2>Details</h2><fieldset>
<legend>Book</legend><div class="display-label">Title</div>
<div class="display-field">@Model.Title</div>
<div class="display-label">ISBN</div>
<div class="display-field">@Model.ISBN</div>
<div class="display-label">Price</div>
<div class="display-field">@String.Format("{0:F}", Model.Price)</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
Add the following code to the Details method of the BookController class.
Collapse | Copy Code
public ActionResult Details(int id)
{
Book book = _db.Books.Find(id);
if (book == null)
return RedirectToAction("Index");
return View("Details", book);
}
Now we will add the Delete View.
Adding the Delete View
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 16/2016ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
1. Right click on the Edit method
2. Select View3. Create a strongly-typed view to Checked4. Select Model class to Book (ASPNETMVCApplication.Models)5. Scaffold template to Delete6. Click on the OK button
Figure 17
It will add the Delete.cshtml file.
Collapse | Copy Code
@model ASPNETMVCApplication.Models.Book
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2><h3>Are you sure you want to delete this?</h3><fieldset>
<legend>Book</legend><div class="display-label">Title</div>
<div class="display-field">@Model.Title</div>
<div class="display-label">ISBN</div>
<div class="display-field">@Model.ISBN</div>
<div class="display-label">Price</div>
<div class="display-field">@String.Format("{0:F}", Model.Price)</div>
</fieldset>
@using (Html.BeginForm()) {
<p>
<input type="submit" value="Delete" /> |
@Html.ActionLink("Back to List", "Index")
</p>
}
Add the following code to the Delete method in the BookController class.
Collapse | Copy Code
public ActionResult Delete(int id)
{
Book book = _db.Books.Find(id);
if (book == null)
return RedirectToAction("Index");
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 17/2017ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
return View(book);
}
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
Book book = _db.Books.Find(id);
_db.Books.Remove(book);
_db.SaveChanges();
return RedirectToAction("Index");
}
Now run the application. Type /Book in the URL and remember that the port number may be
different in your case.
Figure 17
Click Create New Link to add a new book.
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 18/2018ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Figure 18
Figure 19
This way you can edit, delete, and view details of the books.
Conclusion
This article will help you create your own robust ASP.NET MVC application.
Thank you!
License
This article, along with any associated source code and files, is licensed under The Code
Project Open License (CPOL)
About the Author
Abdul Quader Mamun
Founder
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 19/2019ww.codeproject.com/Articles/161402/ASP-NET-Application-Development-Using-MVC
Article Top
Sign Up to vote Poor Excellent Vote
Search this forum Go
V Tech Solution BDBangladesh
Member
I have been developing software/web application since 2002 mainly
on Microsoft technologies. I am a MCSD and MCTS. I have
developed a wide range of Web, Desktop and Mobile applications.
I am vast experience with Telerik technologies.
I am also experience with other technologies.
I am very much fan of Object Oriented Architec tural Framework-
(Design & Pattern) and well organized effective coding.
Blog: Abdul Quader Mamun
Comments and Discussions
You must Sign In to use this message board.
Profile popups Noise Medium Layout Expand Posts & Replie s Per page 10 Update
Refresh First Prev Next
Md. Marufuzzaman 2:13 30 Jun '12
Mamun Bhai, khub bhalo likshen, dakha khub bhalo lagloo.
ThanksMd. Marufuzzaman
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that cancause failure – Thomas Edison.
Sign In ·View Thread · Permalink
Abdul Quader Mamun 2:55 30 Jun '12
Thanks, That's my energy!
Sign In ·View Thread · Permalink
Md. Marufuzzaman 4:37 30 Jun '12
Keep it up
ThanksMd. Marufuzzaman
I will not say I have failed 1000 times; I will say that I have discovered 1000 waysthat can cause failure – Thomas Edison.
Sign In ·View Thread · Permalink
Rajalingam22 23:50 25 Jun '12
Excellent
Re: Excellent
Re: Excellent
very useful
7/31/2019 ASP Example
http://slidepdf.com/reader/full/asp-example 20/20
Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.1207 30.1 | Last Updated 23 Feb 201 1
Article C opyright 2011 by Abdul Quader Mamun
Everything else C opyright © CodeProject, 1999-2012
Terms of Use
Hi Friend, your article is very useful to MVC begginers. Thank you very much..
Sign In ·View Thread · Permalink
José Rafael GiraldoTenorio
11:19 1 Mar '11
I have the e rror: Invalid object name 'dbo.Libroes' in the method:
public ActionResult Index(){var varLibros = from libro in contexto.Librosselect libro; return View(varLibros.ToList()); // Here arise the error!!!}
This is spanish: 'Books == Libros' and 'Book == Libro'I don't know why appear the 'es' chars.
Thanks for your help!!!Rafael
Sign In ·View Thread · Permalink
Seishin# 21:31 24 Feb '11
basic stuff repeated in every single tutorial
life is study!!!
Sign In ·View Thread · Permalink 2.33/5 (2 votes)
shahin_net 23:57 23 Feb '11
This artical is helpfull.
Sign In ·View Thread · Permalink
Abdul Quader Mamun 1:45 24 Feb '11
Thanks for voting.
Sign In ·View Thread · Permalink
kdgupta87 10:31 23 Feb '11
nicely written
Sign In ·View Thread · Permalink
Abdul Quader Mamun 13:47 23 Feb '11
Thanks for voting me.
Sign In ·View Thread · Permalink
Last Visit: 18:00 31 Dec '99 Last Update: 0:39 3 Aug '12 1 2 Next »
General News Suggestion Question Bug Answer Joke Rant
Admin
Layout: fixed |
fluid
Error
[My vote of 1] nothing new
Very Helpfull
Re: Very Helpfull
My vote of 5
Re: My vote of 5