简单的MVC与SQL Server Express LocalDB

  • M模式: 类,表示数据的应用程序和使用验证逻辑以强制实施针对这些数据的业务规则。
  • V视图: 应用程序使用动态生成 HTML 响应的模板文件。
  • C控制器: 处理传入的浏览器请求的类中检索模型数据,然后指定将响应返回到浏览器的视图模板。

简单练习:

1、添加Controller

HelloWorldController:

using System.Web;

using System.Web.Mvc;

namespace MvcMovie.Controllers

{

public class HelloWorldController : Controller

{

//

// GET: /HelloWorld/

public string Index()

{

return "This is my <b>default</b> action...";

}

//

// GET: /HelloWorld/Welcome/

public string Welcome()

{

return "This is the Welcome action method...";

}

}

}

设置中的路由的格式应用程序_Start/RouteConfig.cs文件:

格式:/[Controller]/[ActionName]/[Parameters]

 

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

}

带参数的:

public string Welcome(string name, int numTimes = 1) {

return HttpUtility.HtmlEncode("Hello " + name + ", NumTimes is: " + numTimes);

}

参数传递查询字符串

public string Welcome(string name, int ID = 1)

{

return HttpUtility.HtmlEncode("Hello " + name + ", ID: " + ID);

}

在中应用程序_Start\RouteConfig.cs文件中,添加"Hello"路由:

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

routes.MapRoute(

name: "Hello",

url: "{controller}/{action}/{name}/{id}"

);

}

}

2、添加视图

原生样子:

public ActionResult Index()

{

return View();

}

MvcMovie\Views\HelloWorld\Index.cshtml创建文件。

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>@ViewBag.Title - Movie App</title>

@Styles.Render("~/Content/css")

@Scripts.Render("~/bundles/modernizr")

</head>

<body>

<div class="navbar navbar-inverse navbar-fixed-top">

<div class="container">

<div class="navbar-header">

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

<span class="icon-bar"></span>

<span class="icon-bar"></span>

<span class="icon-bar"></span>

</button>

@Html.ActionLink("MVC Movie", "Index", "Movies", null, new { @class = "navbar-brand" })

</div>

<div class="navbar-collapse collapse">

<ul class="nav navbar-nav">

<li>@Html.ActionLink("Home", "Index", "Home")</li>

<li>@Html.ActionLink("About", "About", "Home")</li>

<li>@Html.ActionLink("Contact", "Contact", "Home")</li>

</ul>

</div>

</div>

</div>

<div class="container body-content">

@RenderBody()

<hr />

<footer>

<p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

</footer>

</div>

@Scripts.Render("~/bundles/jquery")

@Scripts.Render("~/bundles/bootstrap")

@RenderSection("scripts", required: false)

</body>

</html>

@*@{

Layout = "~/Views/Shared/_Layout.cshtml";

}*@

@{

ViewBag.Title = "Index";

}

<h2>Index</h2>

<p>Hello from our View Template!</p>

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>@ViewBag.Title - Movie App</title>

@Styles.Render("~/Content/css")

@Scripts.Render("~/bundles/modernizr")

</head>

HelloWorldController.cs :

using System.Web;

using System.Web.Mvc;

namespace MvcMovie.Controllers

{

public class HelloWorldController : Controller

{

public ActionResult Index()

{

return View();

}

public ActionResult Welcome(string name, int numTimes = 1)

{

ViewBag.Message = "Hello " + name;

ViewBag.NumTimes = numTimes;

return View();

}

}

}

Welcome.cshtml

@{

ViewBag.Title = "Welcome";

}

<h2>Welcome</h2>

<ul>

@for (int i = 0; i < ViewBag.NumTimes; i++)

{

<li>@ViewBag.Message</li>

}

</ul>

3、添加模型

using System;

namespace MvcMovie.Models

{

public class Movie

{

public int ID { get; set; }

public string Title { get; set; }

public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

public decimal Price { get; set; }

}

}

using System;

using System.Data.Entity;

namespace MvcMovie.Models

{

public class Movie

{

public int ID { get; set; }

public string Title { get; set; }

public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

public decimal Price { get; set; }

}

public class MovieDBContext : DbContext

{

public DbSet<Movie> Movies { get; set; }

}

}

SQL Server Express LocalDB

Web.config文件:

<add name="MovieDBContext"

connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf"

providerName="System.Data.SqlClient"

/>

<connectionStrings>

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie-fefdc1f0-bd81-4ce9-b712-93a062e01031;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcMovie-fefdc1f0-bd81-4ce9-b712-93a062e01031.mdf" providerName="System.Data.SqlClient" />

<add name="MovieDBContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf" providerName="System.Data.SqlClient" />

</connectionStrings>

using System;

using System.Data.Entity;

namespace MvcMovie.Models

{

public class Movie

{

public int ID { get; set; }

public string Title { get; set; }

public DateTime ReleaseDate { get; set; }

public string Genre { get; set; }

public decimal Price { get; set; }

}

public class MovieDBContext : DbContext

{

public DbSet<Movie> Movies { get; set; }

}

}

public ActionResult Details(int? id)

{

if (id == null)

{

return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

}

Movie movie = db.Movies.Find(id);

if (movie == null)

{

return HttpNotFound();

}

return View(movie);

}

@model MvcMovie.Models.Movie

@{

ViewBag.Title = "Details";

}

<h2>Details</h2>

<div>

<h4>Movie</h4>

<hr />

<dl class="dl-horizontal">

<dt>

@Html.DisplayNameFor(model => model.Title)

</dt>

@*Markup omitted for clarity.*@

</dl>

</div>

<p>

@Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |

@Html.ActionLink("Back to List", "Index")

</p>

@foreach (var item in Model) {

<tr>

<td>

@Html.DisplayFor(modelItem => item.Title)

</td>

<td>

@Html.DisplayFor(modelItem => item.ReleaseDate)

</td>

<td>

@Html.DisplayFor(modelItem => item.Genre)

</td>

<td>

@Html.DisplayFor(modelItem => item.Price)

</td>

<th>

@Html.DisplayFor(modelItem => item.Rating)

</th>

<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>

</tr>

}

原文地址:https://www.cnblogs.com/zhangsonglin/p/10436554.html

时间: 2024-08-10 03:03:05

简单的MVC与SQL Server Express LocalDB的相关文章

[C#]SQL Server Express LocalDb(SqlLocalDb)的一些体会

真觉得自己的知识面还是比较窄,在此之前,居然还不知道SqlLocalDb. SqlLocalDb是啥?其实就是简化SQL Server的本地数据库,可以这样子说,SQL Server既可以作为远程,也可以做本地, 而SqlLocalDb只能作为本地使用.说的直接一点,SqlLocalDb就是一个轻量级的基于本地的T-SQL数据库,全称:SQL Server Express LocalDb. 好,废话不多说. 第一,怎么安装这个SqlLocalDb? 1)如果安装过Visual Studio 20

Comparison of SQL Server Compact, SQLite, SQL Server Express and LocalDB

Information about LocalDB comes from here and SQL Server 2014 Books Online. LocalDB is the full SQL Server Express engine, but invoked directly from the client provider. It is a replacement of the current "User Instance" feature in SQL Server Ex

ASP.NET MVC与Sql Server交互,把字典数据插入数据库

在"ASP.NET MVC与Sql Server交互, 插入数据"中,在Controller中拼接sql语句.比如: _db.InsertData("insert into Product(Name,quantity,Price) values('"+productVm.Name+"','"+productVm.Quantity+"','"+productVm.Price+"')"); 在某些场景中需要把数

一个简单的Java 连接SQL Server数据库连接驱动类

import java.sql.*; /** * SQL Server数据库连接类 * @author Administrator * */ public class Sqlsdc { static int a = 0; public Connection sqlsdc(String user, String pwd, String dn) { String url = "jdbc:sqlserver://localhost:1433;databaseName="+dn; final

简单的如何创建sql server存储过程

学习sql server数据库,sql server存储过程的建立方法是一定要知道的,下面将教您如何建立sql server存储过程,希望对您有所帮助. 在对象资源管理器中,连接到某个数据库引擎实例,再展开该实例. 展开“数据库”.sql server存储过程所属的数据库以及“可编程性”. 右键单击“存储过程”,再单击“新建存储过程”. 在“查询”菜单上,单击“指定模板参数的值”. 在“指定模板参数的值”对话框中,“值”列包含参数的建议值.接受这些值或将其替换为新值,再单击“确定”. 在查询编辑

使用Visual Studio下自带的SQL Server Express

软件环境:Windows7(x64) + Visual Studio 2010 + SQL Server Express 2008 1.配置数据库 装VS2010不小心把自带的SQL Server 2008 Express也装上了,后来要用SQL Server 2008,试了N多个办法就是装不上,微软的东西这点让人很是不爽.重装系统?No Way!自带的Express版难道不能用?这么非常小巧,要是能用以后就不装又大又难伺候的正式版SQL Server了,网上搜索一下,还真的可以~~ A.打开S

ASP.NET MVC与Sql Server交互, 插入数据

在"ASP.NET MVC与Sql Server建立连接"中,与Sql Server建立了连接.本篇实践向Sql Server中插入数据. 在数据库帮助类中增加插入数据的方法. public class SqlDB { protected SqlConnection conn; //打开连接 public bool OpenConnection() { conn = new SqlConnection(ConfigurationManager.ConnectionStrings[&qu

资料:MVC框架+SQL Server 数据集成引擎

ylbtech-资料:MVC框架+SQL Server 数据集成引擎 1.返回顶部 1. 功能特点: MVC框架耦合性低视图层和业务层分离,这样就允许更改视图层代码而不用重新编译模型和控制器代码,同样,一个应用的业务流程或者业务规则的改变只需要改动MVC的模型层即可.因为模型与控制器和视图相分离,所以很容易改变应用程序的数据层和业务规则.模型是自包含的,并且与控制器和视图相分离,所以很容易改变应用程序的数据层和业务规则.如果把数据库从MySQL移植到Oracle.SQLServer,或者改变基于

[.Net MVC] 使用SQL Server数据库代替LocalDb

之前开发的时候一直用的VS2013,所以数据库也用的LocalDb,这给开发带来很大便利.不过由于开发后还要进行部署,就改用了SQL Server 2012,这里总结下过程. 基本环境:VS2013,EF Code First,SQL Server 2012,Win7. 修改领域层的App.config,就是原来用EF Code First生成数据库的那个项目,用LocalDb的时候,EF节点和连接字符串节点: <entityFramework> <defaultConnectionFa