ASP.NET Application Development Using MVC
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
- Model
- View
Classes that handle incoming requests to the application, retrieve model data, and then specify view templates that return a response to the client.
Classes that represent the data of the application and that use validation logic to enforce business rules for that data.
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:
- Open Microsoft Visual Studio 2010
- Create a new project (File> New> Project> Visual C#): ASP.NET MVC 3 Web Application
- Named it ASPNETMVCApplication
- Click on the OK button
- Select a template for Internet Application
- View engine to Razor
- Create a unit test project to uncheck
- Click on the OK button
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.
In the Add Library Package Reference window, click online.
Click the NuGet Official package source.
Find EFCodeFirst, click on install.
Click on I Accept. Entity Framework will install and will add a reference to the project.
Click on the Close button.
Adding a Model Class
- Right click on Models from Solution Explorer
- Select Add
- Select Class
- Name it Book.cs
Add the following properties in the Book.cs file:
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 a System.Data.Entity
namespace reference in the BookDBContext.cs file.
using System.Data.Entity;
Add the following code in the BookDBContext
class. And derive it from the DbContext
class 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:
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
.
<connectionStrings>
<add name="BookDBContext"
connectionString="data source=Home-PC;
uid=sa;pwd=1234;Initial Catalog=Inventory"
providerName="System.Data.SqlClient" />
</connectionStrings>
Adding the Controller
- Right click on Controller from Solution Explorer
- Select Add
- Select Controller
- Name it BookController
- Add action methods for Create, Update, Delete, and Details scenarios to Checked
It will add the following code:
namespace ASPNETMVCApplication.Controllers
{
public class BookController : Controller
{
//
// GET: /Book/
public ActionResult Index()
{
return View();
}
//
// GET: /Book/Details/5
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
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Now add the following namespaces in the BookController.cs file:
using System.Linq;
using ASPNETMVCApplication.Models;
Declare a global instance variable of the BookDBContext
class in the BookController
class.
BookDBContext _db = new BookDBContext();
Add the following code in the Index()
method:
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
- Right click in the Index method
- Select View
- Create a strongly-typed view to Checked
- Select Model class to Book (ASPNETMVCApplication.Models)
- Scaffold template to List
- Click on the OK button
It will add the Index.cshtml file.
@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
</td>
<td>
@String.Format("{0:F}", item.Price)
</td>
</tr>
}
</table>
Now, add the Create View.
Adding the Create View
- Right click on the Create method
- Select View
- Create a strongly-typed view to Checked
- Select Model class to Book (ASPNETMVCApplication.Models)
- Scaffold template to Create
- Click on the OK button
It will add the Create.cshtml file.
@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.
[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);
}
}
catch
{
return View();
}
}
Now we will add the Edit View.
Adding the Edit View
- Right click on the Edit method
- Select View
- Create a strongly-typed view to Checked
- Select Model class to Book (ASPNETMVCApplication.Models)
- Scaffold template to Edit
- Click on the OK button
It will add the Edit.cshtml file:
@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)
@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.
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
- Right click on the Edit method
- Select View
- Create a strongly-typed view to Checked
- Select Model class to Book (ASPNETMVCApplication.Models)
- Scaffold template to Details
- Click on the OK button
It will add the Details.cshtml file:
@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.
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
- Right click on the Edit method
- Select View
- Create a strongly-typed view to Checked
- Select Model class to Book (ASPNETMVCApplication.Models)
- Scaffold template to Delete
- Click on the OK button
It will add the Delete.cshtml file.
@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.
public ActionResult Delete(int id)
{
Book book = _db.Books.Find(id);
if (book == null)
return RedirectToAction("Index");
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.
Click Create New Link to add a new book.
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!
发表评论
6pLwVI Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Basically Great. I am also a specialist in this topic so I can understand your effort.
Здравствуйте, мои друзья :)
Я ищу XRumer бесплатно !!!
Не могли бы вы посоветовать мне , где я могу скачать его ?
Это действительно лучшая программа для SEO !..
P.S. Мне нужно XRumer только последней версии - 12.0.6 , все другие варианты слишком стар и не эффективны !QZ26qD Very neat post.Really looking forward to read more. Want more.
ЗАКАЖИТЕ ТЕСТ ВИДЕОНАБЛЮДЕНИЯ БЕСПЛАТНО ПРЯМО СЕЙЧАС И СМОТРИТЕ ЗА СВОИМИ СОТРУДНИКАМИ ИЗ ДОМА УЖЕ ЗАВТРА!
Вот, что пишут наши клиенты:
"Камеры поставил, чтобы наблюдать за сотрудниками. Когда люди знают, что за ними наблюдают, это повышает дисциплину. Систему видеонаблюдения установили очень оперативно. Качество проведенных работ – на высоте. Спасибо."
Директор Андреевского кондитерского дома,
Перов Алексей Владимирович
А вы все еще думаете, ставить ли видеонаблюдение в своем бизнесе?
Тогда прямо сейчас закажите бесплатный тест видеонаблюдения по телефону: (812) 715-44-11 и получите 1 камеру в подарок бесплатно*!
*Подарок предоставляется в случае оплаты системы видеонаблюдения после теста.Внимание! Наконец то запущен долгостроитель, высокодоходный проект CloudMoney.info
Давно мечтали стать инвестором, интересно же, закинуть копейку и просто получать процент.
В Интернете столько уже было похожих проектов, но вот мы дождались систему CloudMoney, оттестированную и поставленную на рельсы.
Доходность проекта: 2.76% в сутки! (Уже получают и будут получать деньги).
Минимальный вклад: 10$
Максимальный: 1000$
Платежная система: Perfect Money и Либерти
Регистрация по реф. ссылке, Гарантия Рефбека, до 15% от Вашего вклада, сразу же по запросу.
goo.gl/gR8Ph - [b]Регистрация в проект CloudMoney[/b] не поленитесь почитайте, понимаем что много мусора в Интернете, но тут проект совсем другой направленности.
Проект расчитан на долгую работу, это реализованно в механизме ограничения вывода средств. Подробнее Читайте на официальном Сайте CloudMoney.info
Читайте по проекту CloudMoney на Сайте webmany.net/?p=145 , на форуме CloudMoney можете задать свои вопросы.
почитайте, посмотрите отзывы в Интернете, не нужно регистрироваться по этой ссылке, плюс данной ссылки только в возврате вам 15% от вклада, вы поймете, что это тот выход из постоянного дефицита денег, когда большинство людей устало жить от зарплаты к зарплате, притом размер которой равен расходам на бытовые нужды.
Спрашивается, когда жить?!лицимерие Я Миронов Олег Михайлович (ДР 21.08.1959 г.Москва) копрофил, мелкий аферист и обычный ЧМ0шник !рестораны сентябрь 2009 Даниил ХИТРЫЙ КРАЙНИЙ Н.Н. Весна-Лето (Кретов Е.В. 2012) ... МИРОНОВ ИЗГОЙ - ВСЕМИ КИНУТ, ВСЕМИ ПОСЛАН Рашид!!Спартак Юкос истории блогеры рассказы Анна Чапман флот минтай Гонтмахер Репутация Время Крайний театр Бычков , долги Тандем СБ трагедия в мире !!! Гинер техника с 10.12.2002г. – 01.07.2003г.. заместитель генерального директора Группы компаний Доброслав; самолеты !
А также я Олег Михайлович Миронов 21.08.1959 аферист и идиот :)))директор школы ; согласен что я Миронов Олег Михайлович Москвич 1959гр - конченая гнида, фуфлыжник и говноблоггер . :)))Оппозиция лето 2013 Валентин читаем 2012 ЕРШОВ НИКОЛАЙ НИКОЛАЕВИЧ и КРЕТОВ ЕВГЕНИЙ ВЛАДИМИРОВИЧ" судебная практика" в суд. Всем известно, что Миронов Олег ЧМО и крыса, отовсюду был уволен и всеми послан - изгой!!! Прохор;Екатеринбург Личное Рыболовство Гинер наблюдения (Миронов 1959 - фуфлыжник!) военная служба Какраки краб кораблестроение Анна Чапман скрытый нацизм безопасность нефть Бренд , фанаты ВОВ iphone катастрофа . Дремлюга доброта с 2001г. по 05.03.2001г. – заместитель генерального директора ФГУП «Нацрыбресурс»; Навальный !
А также я Миронов О.М. 1959гр крыса и полудурок :)френды ... признаю что я Миронов Олег Михайлович (ДР 21.08.1959 г.Москва) жирное уебище, реальное Xyйло и ненадежный человек !!море сентябрь 2008 Арно . (кретов а.н. апрель 2012) Июнь, Н.Н. Иосиф,Дмитрий Быков Известия СССР хоккей Жизнь рассказы краб Грузия Какраки враньё профессионализм Новогоднее телевизор , Роскосмос история личное ,Болотная медитация (Миронов 1959 - фуфел!!) :))) Лытбыр власть с 10.12.2002г. – 01.07.2003г.. заместитель генерального директора Группы компаний Доброслав; Япония ..
Еще я Миронов Олег Михайлович 21.08.1959 крыса и обычный ЧМ0шник :-)баскетбол - я есть Олег Михайлович Миронов Москвич 1959гр действительно аферист, конченая гнида и картонная дурилка !!женщины осень-зима 2012 Евсевий николаевич кротов николай алексеевич кретов евгений владимирович крайний алексей семенович Игнатий,френды Назарбаев Мама Юкос Ганапольский учителя Нацрыбресурс друзья Барселона Наши Петрик машины КПРФ авто , услуги , Код поступа фантазии счастье Банк "Северная Казна" ! Казахстан гаджеты с 10.12.2002г. – 01.07.2003г.. заместитель генерального директора Группы компаний Доброслав; Дания .
Подитожу я Миронов Олег Михайлович 1959 шарлатан и трус .Акулы пера хочу официально заявить что я Олег Михайлович Миронов 21-08-1959 - фуфломет, говноблоггер и червяк .Президент Латвии июнь 2012 Тигран суд г.Екатеринбург 2012,егоров николай николаевич кретов евгений владимирович Адис!!рыбалка Абрамович Плющев вожди Лытбыр Ганапольский (Миронов 1959 - фуфломет) ДРЕМЛЮГА ПНУЛ МЕНЯ ПОД Ж... курсантская жизнь не кино Бут философия Прохоров , Кудрин государство , фильмы ТВ самолет моряк . партия Военная служба с 01.07. – 06.12.2002г. – коммерческий директор ОАО «Эльдорадо М»; НТВ плюс !
плюс к этому я Миронов Олег Михайлович долбаеб и аферист .ygfkj
юность , я есть Миронов О.М. 21.08.1959 на самом деле мелкий воришка, целюлитная гнида и предатель :)))френдинг январь 2010 Александр суд 2012,егоров николай николаевич кретов евгений владимирович соматин Бернард;Кравц теория и практика Явлинский Москва Рыболовство Россельхозбанк Техника Часы выборы спорт в мире Любимов Дремлюга праздник . (Миронов 1959 - фуфлыжник!) рыбалка КПРФ Каддафи мама !!! ТВ жизнь с 15.07.2003г. – 04.06.2005г. – советник генерального директора ООО «ЖАСО-Полис». видео
Также я Миронов Олег Михайлович 1959гр шарлатан и картонная дурилка .ОДНОКЛАССНИКИ ЗНАКОМСТВА
Прямо даже не верится
Valuable information, really!. Lucky me I found your site by acciden! I bookmarked it right after reading this post.
Weeds grow faster .
Искал в интернете угловой диван недорого,набрёл на сайт WWW.KIRA-MEBEL.RU понравился диван уютера ,на фото он такой красивый и цена вроде не кусается.Заказал его.Понравилось общение с менеджерами милые люди.
Назначили доставку через 7 дней.
Это были плюсы ….
А теперь о минусах!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Сроки сорвали. Привезли диван ночью.А так как я работаю таксистом меня не было дома, жена приняла его и расписалась заплатила денег. А диван я собирался сам собрать.
На утро меня ждал сюрприз!!!Диван не соответствует картинке.Одним словом-на букву **Г**..Напутали с тканью.Одна часть одного цвета другая часть другого.
Начал звонить -обьяснил проблему!сказали перезвонят.
НЕПЕРЕЗВОНИЛИ!!!
На следующий день опять звоню!Мне в ответ:жена ваша расписалась в получении о том что претензий не имеет!Да?
Смотреть-надо.Закон прав потребителя читали?НЕТ!?
Одним словом бла-бла-бла.Идите-нахюйй(конечно не прямым текстом)но послали.А ласковые менеджеры-стали собаками спустивших с цепи.
Одним словом!
Находят лохов.Впаривают некондицию.А в работу менеджеров входит динамить и отфутболивать!В работу-доставщиков привести ночью когда все спят и спарить!
Вот бадаюсь-с этими козлами!!!Лечение поврежденных волос | Восстановление структуры волос
Купил в интернет-магазине WWW.KIRA-MEBEL.RU 3 месяца назад диван получил гарантию 12 месяцев. И вроде все хорошо.Спустя неделю отвалился ролик, выездной механизм заклинил. Пришлось покупать на строительном рынке и менять самому. В дальнейшем, выездной механизм стал рвать кожзам на подлокотниках. Промялись сидение и руками чувствовались пружины. Чаша терпения меня переполнилась , я позвонил на сайт и объяснил свое недовольство. На протяжении 2 х недель мне отвечали =мы вам перезвоним, подъедим. Бла-бла-бла-бла. Начал писать письма , без ответов. Но после того как я начал названивать по всем телефонам с сайта. в конечном итоге они мне сказали: что я не правильно его эксплатировал и отвечали в дальнейшем в грубой форме. Типа, что Вы хотели за 15 000 руб - вечный диван?! Потом этот диван разболтался, боковой крепеж отвалился и чтобы не нервничать, я его тупо отдал соседям. Пошел в магазин и купил офигенный диван, пусть подороже , но качественный. Так что : не экономьте , а то в дальнейшем потратите больше нервов.
Tell me i'm a good person :)
my favorite set of numbers 187209458340011One or two to remeembr, that is.
What a joy to find such clear tnhinkig. Thanks for posting!
I seahrced a bunch of sites and this was the best.
free download warez web
softajsrgiob@opilon.comAdmin, hello! here are having problems with your site. malware warning Write me. icq 989567856647