第1章 (ASP.NET MVC简介)

一.MVC概念

MVC由三部分组成:视图(View)、模型(Model)、控制器(Controller)组成

二.运用VS创建MVC

1、新建一个“解决方案”

2、在”解决方案“右键新建“ASP.NET MVC3 APPliction ”

如图所示:

第1章  (ASP.NET MVC简介)

3、选择"Internet应用程序",视图引擎为“Razor”

如图所示:

第1章  (ASP.NET MVC简介)

4、建完后添加“表示层”与“数据库访问层”并且添加引用关系

5、在”数据访问层“添加“ADO.NET实体数据模型”

如图所示:

第1章  (ASP.NET MVC简介)

6、选择“从数据库生成”,后台获取信息

如图所示:

第1章  (ASP.NET MVC简介)

7、选择要获取数据库表名

如图所示:

第1章  (ASP.NET MVC简介)

8、选择“否”,视图名字可以改,这里我就不改了

如图所示:

第1章  (ASP.NET MVC简介)

9、选择相对应表名,这里就只有一个表

如图所示:

第1章  (ASP.NET MVC简介)

10、编辑”表示层“,但是会报错,是因为缺少“插件”

如图所示:

第1章  (ASP.NET MVC简介)

解决方法是:如图所示

第1章  (ASP.NET MVC简介)

代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using LinqService; //引用
namespace LinqBLL
{
public class ProductBll
{
public List<Product> GetProduct()
{
using (SportsStoreEntities se = new SportsStoreEntities())
{
var products = se.Product; //数据库里面表名称
return products.ToList();
}
}
}
}

11、在“表示层”编写获取数据库方法

代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; using ProducrService;
using ProductBLL;
namespace ProductMvC.Controllers
{
public class HomeController : Controller
{
Producrbll bll = new Producrbll();
public ActionResult Index()
{
ViewBag.Message = "欢迎使用 ASP.NET MVC!"; return View();
}
//获取产品
public ActionResult List()
{
List<Product> ps = bll.GetProduct();
return View(ps);
} public ActionResult About()
{
return View();
}
}
}

图片示例:

第1章  (ASP.NET MVC简介)

12、在"List"方法单击右键“添加视图”后,选择相关对应类型

如图所示:

第1章  (ASP.NET MVC简介)

添加完成后代码:如果难看,可以添加或修改一些标签与样式

@model IEnumerable<ProducrService.Product>

@{
ViewBag.Title = "List";
} <h2>List</h2> <p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Name
</th>
<th>
nDescription
</th>
<th>
Category
</th>
<th>
Price
</th>
<th>
Image
</th>
<th></th>
</tr> @foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.nDescription)
</td>
<td>
@Html.DisplayFor(modelItem => item.Category)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Image)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
@Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProductID })
</td>
</tr>
} </table>

13、添加后,在“Views”文件里面的"Shared"文件里面"[@]_Layout.cshtml"页面修改些内容

代码示例:

<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.7..min.js")" type="text/javascript"></script>
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1>在线产品</h1>
</div>
<div id="logindisplay">
@Html.Partial("_LogOnPartial")
</div>
<div id="menucontainer">
<ul id="menu">
<li>@Html.ActionLink("主页", "Index", "Home")</li>
<li>@Html.ActionLink("产品", "List", "Home")</li>
<li>@Html.ActionLink("关于", "About", "Home")</li>
</ul>
</div>
</div>
<div id="main">
@RenderBody()
</div>
<div id="footer">
</div>
</div>
</body>
</html>

如图所示:

第1章  (ASP.NET MVC简介)

14、最后运用Web.config连接数据库,先找到APP.config配置文件

如图所示:

第1章  (ASP.NET MVC简介)

代码示例:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="SportsStoreEntities" connectionString="metadata=res://*/Products.csdl|res://*/Products.ssdl|res://*/Products.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=SportsStore;user id=sa;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

复制到Web.config且替换掉

如图所示:

第1章  (ASP.NET MVC简介)

代码示例:

<?xml version="1.0" encoding="utf-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="" minRequiredPasswordLength="" minRequiredNonalphanumericCharacters="" passwordAttemptWindow="" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<!--<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-ProductMvC-20170104161258;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-ProductMvC-20170104161258.mdf" />
</connectionStrings>-->
<connectionStrings>
<add name="SportsStoreEntities" connectionString="metadata=res://*/Products.csdl|res://*/Products.ssdl|res://*/Products.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=SportsStore;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>

最后运行结果:

第1章  (ASP.NET MVC简介)

上一篇:ASP.NET MVC教程一:ASP.NET MVC简介


下一篇:ASP.NET MVC简介