Here we create a simple ASP. net mvc practice application to CRUD the News table of the News Database.
I. preparations:
Create a News Database News table in SQLServer, add the NewsData. dbml file to the Models folder, and drag the News table to the dbml file.
2. Create News
1. Add a view
Add the News folder to the Views folder, right-click the News folder and choose "add"> "View" from the shortcut menu, and then select the View as follows (note that you need to compile the View before adding it, otherwise, the class in the Model cannot be displayed)
The generated code is as follows: (slightly modify and remove the id line)
<% @ Page Title = "" Language = "C #" MasterPageFile = "~ /Views/Shared/Site. Master "Inherits =" System. Web. Mvc. ViewPage <MvcCRUDDemo. Models. News> "%>
<Asp: Content ID = "Content1" ContentPlaceHolderID = "TitleContent" runat = "server">
Create
</Asp: Content>
<Asp: Content ID = "Content2" ContentPlaceHolderID = "MainContent" runat = "server">
<H2> Create
<% = Html. ValidationSummary ("Create was unsuccessful. Please correct the errors and try again.") %>
<% Using (Html. BeginForm () {%>
<Fieldset>
<Legend> Fields </legend>
<P>
<Label for = "Title"> Title: </label>
<% = Html. TextBox ("Title") %>
<% = Html. ValidationMessage ("Title", "*") %>
</P>
<P>
<Label for = "Content"> Content: </label>
<% = Html. TextBox ("Content") %>
<% = Html. ValidationMessage ("Content", "*") %>
</P>
<P>
<Label for = "Author"> Author: </label>
<% = Html. TextBox ("Author") %>
<% = Html. ValidationMessage ("Author", "*") %>
</P>
<P>
<Label for = "CreateTime"> CreateTime: </label>
<% = Html. TextBox ("CreateTime") %>
<% = Html. ValidationMessage ("CreateTime", "*") %>
</P>
<P>
<Label for = "Country"> Country: </label>
<% = Html. TextBox ("Country") %>
<% = Html. ValidationMessage ("Country", "*") %>
</P>
<P>
<Input type = "submit" value = "Create"/>
</P>
</Fieldset>
<% }%>
<Div>
<% = Html. ActionLink ("Back to List", "Index") %>
</Div>
</Asp: Content>
Inherits = "System. Web. Mvc. ViewPage <MvcCRUDDemo. Models. News>" in the first line indicates that the Model of this View is MvcCRUDDemo. Models. News. In addition, we will discuss the input verification in Series 3.
2. Add Controler
Right-click the Controller folder to add-"Controller
Public ActionResult Create ()
{
News news = new News {CreateTime = DateTime. Now };
Return View (news );
}
[AcceptVerbs (HttpVerbs. Post)]
Public ActionResult Create (News news)
{
NewsDataDataContext dc = new NewsDataDataContext ();
Dc. News. InsertOnSubmit (news );
Dc. SubmitChanges ();
Return RedirectToAction ("NewsList ");
}
- 2 pages in total:
- Previous Page
- 1
- 2
- Next Page