简单的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>© @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>
}
简单的MVC与SQL Server Express LocalDB的更多相关文章
- [C#]SQL Server Express LocalDb(SqlLocalDb)的一些体会
真觉得自己的知识面还是比较窄,在此之前,居然还不知道SqlLocalDb. SqlLocalDb是啥?其实就是简化SQL Server的本地数据库,可以这样子说,SQL Server既可以作为远程,也 ...
- 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 ...
- 如何安全的将VMware vCenter Server使用的SQL Server Express数据库平滑升级到完整版
背景: 由于建设初期使用的vSphere vCenter for Windows版,其中安装自动化过程中会使用SQL Server Express的免费版数据库进行基础环境构建.而此时随着业务量的增加 ...
- SQL SERVER EXPRESS 连接字符串
Microsoft SQL Server Express Edition 为生成应用程序提供了一个简单的数据库解决方案.SQL Server Express Edition 支持完整的 SQL Ser ...
- 无法定位 Local Database Runtime 安装。请验证 SQL Server Express 是否正确安装以及本地数据库运行时功能是否已启用。
错误描述: 在与 SQL Server 建立连接时出现与网络相关的或特定于实例的错误.未找到或无法访问服务器.请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接. (provide ...
- 使用Visual Studio下自带的SQL Server Express
软件环境:Windows7(x64) + Visual Studio 2010 + SQL Server Express 2008 1.配置数据库 装VS2010不小心把自带的SQL Server 2 ...
- SQL Server与SQL Server Express的区别
SQL Server Express 2005(以下简称 SQLExpress) 是由微软公司开发的 SQL Server 2005(以下简称 SQL2005)的缩减版,这个版本是免费的,它继承了 S ...
- ASP.NET MVC与Sql Server交互,把字典数据插入数据库
在"ASP.NET MVC与Sql Server交互, 插入数据"中,在Controller中拼接sql语句.比如: _db.InsertData("insert int ...
- ASP.NET MVC与Sql Server交互, 插入数据
在"ASP.NET MVC与Sql Server建立连接"中,与Sql Server建立了连接.本篇实践向Sql Server中插入数据. 在数据库帮助类中增加插入数据的方法. p ...
随机推荐
- xml--myeclipse用快捷键注释xml语句
7.5以上版本才可以ctrl+shift+/ 撤销注释:CTRL + SHIFT + \ 参考:https://blog.csdn.net/tengdazhang770960436/article/d ...
- docker中crontab无法执行
1.下载的镜像是ubuntu最简版,默认没有安装crontab 2.业务需求需要crontab 最早解决方案 1.在宿主机里面 1 3 * * * root cd /data/wwwroot/xx ...
- 在TensorFlow中运行程序多次报错:AttributeError: __exit__
我没有记住语句 with tf.Session() as sess: 多次写成了 with tf.Session as sess: 吃括号这个低级的错误又犯了,真不应该,立下flag:以后再犯相同的错 ...
- Unity3d之如何截屏
Unity3d中有时有截屏的需求,那如何截屏呢,代码如下: /// <summary> /// 截屏 /// </summary> /// <param name=&qu ...
- python3 TypeError: a bytes-like object is required, not 'str'
在学习<Python web开发学习实录>时, 例11-1: # !/usr/bin/env python # coding=utf-8 import socket sock = sock ...
- sql server得到某个数据库的所有表和所有字段
select b.name tablename,a.name as columnnamefrom sys.columns a,sys.objects b,sys.types cwhere a.obje ...
- Spark学习之路 (九)SparkCore的调优之数据倾斜调优
摘抄自:https://tech.meituan.com/spark-tuning-pro.html 数据倾斜调优 调优概述 有的时候,我们可能会遇到大数据计算中一个最棘手的问题——数据倾斜,此时Sp ...
- c++学习笔记(八)- map
map<key, value>是按key排好序的,key不可以重复. 1. map.lower_bound():按key查找,如果查找的key存在,返回该位置,如果不存在返回大于所查找值的 ...
- 干货 | JavaScript内存空间详解
JS栈内存与堆内存 var a = 20; var b = 'abc'; var c = true; var d = { m: 20 } 因为JavaScript具有自动垃圾回收机制,所以对于前端开发 ...
- 20165316 技能学习心得与c语言学习
20165316 技能学习心得与c语言学习 一.技能学习经验 我会打乒乓球,在中国,我只能说我"会"打,至于"比大多数人更好"我不敢断言,因为我无时无刻不感受到 ...