asp.net MVC3 hands-on teaching you to build web_ practical skills

Source: Internet
Author: User

Development tools: vs2010+mssql2005, you need to use MVC3.0

Environment configuration

The first step: to the official website download MVC3, provides simplified Chinese. Install AspNetMVC3ToolsUpdateSetup.exe First, then install AspNetMVC3ToolsUpdateVS11Setup.exe

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=1491

Step Two: Create a new database and test the table. and insert some test data into the table.

Use [Yancomdb] 
go 
/****** object: Table [dbo].[ Newsentity] Script Date: 03/12/2012 22:03:59 ******/ 
SET ansi_nulls on 
go 
SET quoted_identifier 
in Go CREATE TABLE [dbo]. [Newsentity] ( 
 [NId] [int] IDENTITY (1,1) not NULL, 
 [Title] [nvarchar] (m) COLLATE chinese_prc_ci_as NOT NULL, 
 [ Information] [text] COLLATE chinese_prc_ci_as null, 
 [TIME] [datetime] NOT NULL CONSTRAINT [Df_newsentity_time] DEFAULT (GETDATE ()), 
 CONSTRAINT [pk_newsentity] PRIMARY KEY CLUSTERED 
( 
 [NId] ASC 
) with (Pad_ INDEX = off, Ignore_dup_key = off) on [PRIMARY] 

Build List Page

Step one: Open vs, new Select MVC3 Web application, enter project name and directory

Second Step: Create Newsentity class, this article uses its own hand-realism class (not using LINQTOSQL,EF, etc. orm)

[Tableattribute ("newsentity")]//this line is important because the MVC framework defaults to finding the table name of the class name complex in db, public 
 class newsentity 
 { 
  [key]//setting primary key public 
  int NId {get; set;} 
 
  [Stringlength (100)]//set authentication information 
  [Required (errormessage= "title cannot be empty"] 
  [DisplayName ("title")] public 
  string Title {get; set;} 
 
  [Required (errormessage = "text must be filled out")] 
  [DisplayName ("Body")] 
  public string Information {get; set;} 
 
  Public DateTime time {get; set;} 
 

Step Three: Configure database connection characters, and note that name here corresponds to the class name that is created in the next step.

<connectionStrings> 
<add name= "projectentity" connectionstring= "Data source=ip;initial catalog= Yancomdb; Persist Security info=true; User id=; password= " 
providername=" System.Data.SqlClient "/> 
</connectionStrings> 

Fourth step: Create Projectentity class, need to inherit DbContext

public class Projectentity:dbcontext 
 {public 
  dbset<newsentity> newsentity {get; set;} 
 } 

Fifth step: New controller,

Projectentity PE = new projectentity (); 
  Public ActionResult News () 
  { 
   try 
   { 
    var list = PE. Newsentity.tolist (); 
    return View (list); 
   catch (Exception e) 
   { 
    throw e; 
   } 
  } 

Step Sixth: Right-click on news and create a new view. Check "Create strong type View", select Newsentity, bracket module SELECT list


Once added, the cshtml code is as follows:

 @model ienumerable<taiqiu.models.newsentity> @{viewbag.title = "Backstage News management list"; 
Layout = "~/views/shared/_mlayout.cshtml";  
 

The post-run effect chart is as follows:


The first list page is completed (no paging is involved and subsequent updates are made). About additions, modifications, and deletions are easy.

Add controller code:

[HttpPost] 
  [ValidateInput (false)] 
  Public ActionResult Create (newsentity News) 
  { 
   if (modelstate.isvalid) 
   { 
    News. Time = DateTime.Now; 
    PE. Newsentity.add (news); 
    Try 
    { 
     PE. SaveChanges (); 
     Return redirecttoaction ("News"); 
    } 
    catch (Exception e) 
    { 
     throw e; 
    } 
 
   } 
   return View (); 
  } 

To add a page:

@model TaiQiu.Models.NewsEntity @{viewbag.title = "Add News"; 
Layout = "~/views/shared/_mlayout.cshtml"; &lt;h2&gt; Add news &lt;/h2&gt; &lt;script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")" Type= "text/ JavaScript "&gt;&lt;/script&gt; &lt;script src=" @Url. Content ("~/scripts/jquery.validate.unobtrusive.min.js") "type = "Text/javascript" &gt;&lt;/script&gt; &lt;script src= "@Url. Content (" ~/scripts/kindeditor/kindeditor.js ")" Type= " Text/javascript "&gt;&lt;/script&gt; &lt;script src=" @Url. Content ("~/scripts/kindeditor/lang/zh_cn.js") "Type=" 
  Text/javascript "&gt;&lt;/script&gt; &lt;script type=" Text/javascript "&gt; var editor; Kindeditor.ready (function (K) {editor = k.create (' textarea[name= ' information '] ', {allowfilemanager:true}) 
  ; 
}); &lt;/script&gt; @using (Html.BeginForm ()) {@Html. ValidationSummary (True) &lt;fieldset&gt; &lt;legend&gt;News&lt; /legend&gt; &lt;div class= "Editor-label" &gt; @Html. Labelfor (model =&gt; model. Title) &lt;/div&gt; &lt;div class= "Editor-field" &gt; @Html. Textboxfor (model =&gt; model. Title, new {style = "width:500px"}) @Html. validationmessagefor (model =&gt; model. Title) &lt;/div&gt; &lt;div class= "Editor-label" &gt; @Html. Labelfor (model =&gt; model. Information) &lt;/div&gt; &lt;div class= "Editor-field" &gt; @Html. Textareafor (model =&gt; model. Information, new {style= "width:800px;height:400px"}) @Html. validationmessagefor (model =&gt; model. Information) &lt;/div&gt; &lt;p&gt; &lt;input type= "Submit" value= "Create"/&gt; &lt;/p&gt; &LT;/FIELDSET&G 
T  } &lt;div&gt; @Html. ActionLink ("Return list", "Index") &lt;/div&gt;

Modifying a page, controller slightly modified:

[HttpPost] 
  [ValidateInput (false)] 
  Public ActionResult Editnews (newsentity News) 
  { 
   if (modelstate.isvalid) 
   { 
    News. Time = DateTime.Now; 
    PE. Entry (News). state = entitystate.modified;//Modify 
    PE. SaveChanges (); 
    Return redirecttoaction ("News"); 
   } 
   Return View (news); 
  } 

Delete Controller code:

Public ActionResult deletenews (int id) 
  { 
   var model = PE. Newsentity.find (ID); 
   PE. Newsentity.remove (model); 
   PE. SaveChanges (); 
   Return redirecttoaction ("News"); 
  } 

Small series Just contact MVC3, this article is just a little accumulation of my study, there are many bad places, I hope we have more to mention the meaning.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.