Vous êtes sur la page 1sur 11

BASIC ASP.

NET MVC REVISITED BUILD A SIMPLE NEWS SITE WITH EF FEATURE CTP4 AND SQL 4 CE PART 1 Author : tumivn | Creator : tumivn Attach Files SimpleBlog.zip I want to build a small news site for me, that will use EF feature CTP4 to access a SQL 4 CE database and ASP.NET MVC 3.0 as front end.

Some weeks ago, Microsoft introduced developers: EF feature CTP4 SQL 4 Compact Edition Web Matrix And today I want to build a small news site for me, that will use EF feature CTP4 to access a SQL 4 CE database and ASP.NET MVC 3.0 as front end. Since we program Geeksship.com and other website, we always use ajax via jQuery to implement almost functions, and that is the reason why I feel hard to implement a traditional CRUD ASP.NET MVC Application. Before writing this topic, Id revisited some to http://asp.net/mvc topics to re-learn how to program CRUD application ^_^. The existance of EF feature CTP4 will help us to build up an aplication with code-first style (code first and then look back to the database to see what EF generate for our application). This is the same thing when we use NHibernate and Fluent NHibernate to program, after implementing all entity classes, we just call a simple sentence and the database is generated. What we need to install before begin? Visual Studio 2010 installed EF feature CTP 4 installed (Click the follow link to download: http://www.microsoft.com/downloads/en/details.aspx? displaylang=en&FamilyID=4e094902-aeff-4ee2-a12d-5881d4b0dd3e ) Web Matrix (this will included SQL 4 CE) and Web Matrix will help us to explore SQL 4 CE database file after coding (Download the Web Platform Installer 3 Beta and choose to install Web Matrix: http://www.microsoft.com/web/webmatrix/download/ ).

After doing all the above things, let start by creating a new asp.net mvc project called SimpleBlog (just for fun!, I will implement a full-feature blog). Remember to add reference to Microsoft.Data.Entity.CTP.dll Create Data Model Classes I want to create 2 tables PressCategory and Press:

using System.ComponentModel.DataAnnotations; namespace SimpleBlog.Models { public class PressCategory { [Key] [StoreGenerated(StoreGeneratedPattern.Identity)] public int Id { get; set; } [Required] public string Name { get; set; } public string Abstract { get; set; } } }

using System.ComponentModel.DataAnnotations; namespace SimpleBlog.Models { public class Press { [Key] [StoreGenerated(StoreGeneratedPattern.Identity)] public int Id { get; set; } [Required] public string Title { get; set; } public string Abstract { get; set; }

public string Body { get; set; }


} } public virtual PressCategory Category { get; set; }

[StoreGenerated(StoreGeneratedPattern.Identity)]

attribute is used to define that Id field is

an identity field . Then we create a DbContext class to access database

using System.Data.Entity; namespace SimpleBlog.Models { public class SimpleBlogDbContext: DbContext { public DbSet<PressCategory> PressCategories { get; set; } public DbSet<Press> Presses { get; set; } } }

And remember that we will use SQL 4 CE, so you must add the below bold sentences to Application_Start method of Global.asax.cs

protected void Application_Start() { Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0"); AreaRegistration.RegisterAllAreas();

RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }

Ok! Weve just finished the back end, and now the front end. At first step, we create a new controller PressCategoryController and edit the Index action:

public class PressCategoryController : Controller { readonly SimpleBlogDbContext _db = new SimpleBlogDbContext(); // // GET: /PressCategory/ public ActionResult Index() { var categories = (from category in _db.PressCategories select category).ToList(); return View(categories); }

Then edit the Index.aspx

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<IList<SimpleBlog.Models.PressCategory >>" MasterPageFile="~/Views/Shared/Site.Master" %> <asp:Content runat="server" ID="Title" ContentPlaceHolderID="TitleContent"> </asp:Content> <asp:Content runat="server" ID="Main" ContentPlaceHolderID="MainContent"> <table> <tr> <th> Id </th>

%>

Name </th> <th> Abstract </th> <th>Actions</th> </tr> <%foreach (var cat in Model) {%> <tr> <td> <%:cat.Id %> </td> <td> <%:cat.Name %> </td> <td> <%:cat.Abstract %> </td> <td> <%:Html.ActionLink("Edit", "Edit", new {id=cat.Id}) %> <%:Html.ActionLink("Delete", "Delete", new {id=cat.Id})

<th>

</td> </tr> <%} %> </table> </asp:Content>

Let run and see what happen when we type url: PressCategory/Index

Ok! It run correctly, and we know that a new database was created in App_Data folder named SimpleBlog.Models.SimpleBlogDbContext.sdf, but remember that we still can not

open this file using SQL Management Studio or Visual Studio 2010, so we open web maxtrix, create a website by open project folder and then open the the db file:

And we open the PressCategory table definition to see as if Id field is primary and identity

The second step is to create Create PressCategory function. We open the PressCategoryController and add two create function

[HttpGet] public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(PressCategory category) { if (ModelState.IsValid) { _db.PressCategories.Add(category); _db.SaveChanges(); return RedirectToAction("Index"); } return View(category); }

And create Create view

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<SimpleBlog.Models.PressCategory>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Create </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Create</h2> <% using (Html.BeginForm()) {%> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%--<div class="editor-label"> <%: Html.LabelFor(model => model.Id) %> </div>

<div class="editor-field"> <%: Html.TextBoxFor(model => model.Id) %> <%: Html.ValidationMessageFor(model => model.Id) %> </div>--%> <div class="editor-label"> <%: Html.LabelFor(model => model.Name) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Name) %> <%: Html.ValidationMessageFor(model => model.Name) %> </div> <div class="editor-label"> <%: Html.LabelFor(model => model.Abstract) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Abstract) %> <%: Html.ValidationMessageFor(model => model.Abstract) </div> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <div> <%: Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> <p>

%>

Remember to comment the model.Id field, because Id is defined as an identity so that we can not edit it.
Run app again and test the PressCategoryController create function

Edit & delete actions:

public ActionResult Edit(int id) { return View(_db.PressCategories.Find(id)); } [HttpPost] public ActionResult Edit(int id, FormCollection collection) { var pressCategory = _db.PressCategories.Find(id); try { UpdateModel(pressCategory); _db.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); }

public ActionResult Delete(int id) { var pressCategory = _db.PressCategories.Find(id); return pressCategory == null ? View("NotFound", id) : View(pressCategory); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Delete(int id, string confirmButton) { var pressCategory = _db.PressCategories.Find(id); if (pressCategory == null) return View("NotFound"); _db.PressCategories.Remove(pressCategory); _db.SaveChanges(); return RedirectToAction("Index"); }

Delete and edit views you can access by downloading attachment.


Voila, it is the end of part 1. Part 2 will be post in 15/09/2010.

Thanks for reading! Please register to be a member of Geeksship.com and download the attachment within thic topic!

Tumi, Le

Vous aimerez peut-être aussi