简单的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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


根据官网 入门 express
java叫接口control什么的app.get.post等等都是请求方式我们可以在游览器输入localhost端口/或者在Apifox里面写。
为了前端丢进去的时候可以直接判断中间件就是经过了这个就会被使用可以做一些自己的数据处理什么的。
Express 文件的上传和下载
运行命令下载app.js 增加中间件。
基本模板来的 后面用后就有什么加什么都行。
此篇完成 增删 刷新文件 的基本操作
最基本的创建 以及 添加了其他的一些插件 登录接口和四个接口
由于每个接口都要放就很麻烦 所以做个中间件
1importre234defstrip_operate(exp):#合并多余的操作符5exp=exp.replace("+-","-")6exp=exp.replace("--","+")7returnexp8910defcal_exp_son(exp_son):#计算两数的乘除11if&
 socket.html<script>//高级api不兼容socket.io//http单向的,socket是双向的,传输都靠tcpletsocket=newWebSocket('ws://localhost:3000')socket.onopen=()=>{//多个页面通信就是先发给服务器,服务器再发给另一个页面socket.send('我
M模式:类,表示数据的应用程序和使用验证逻辑以强制实施针对这些数据的业务规则。V视图:应用程序使用动态生成HTML响应的模板文件。C控制器:处理传入的浏览器请求的类中检索模型数据,然后指定将响应返回到浏览器的视图模板。简单练习: 1、添加ControllerHelloWorldControlle
在Node开发中免不了要使用框架,比如express、koa、koa2拿使用的最多的express来举例子开发中肯定会用到很多类似于下面的这种代码varexpress=require('express');varapp=express();app.listen(3000,function(){console.log('listen3000...');});app.use(middle
node的http创建服务与利用Express框架有何不同原生http模块与使用express框架对比:consthttp=require("http");letserver=http.createServer(function(req,res){//服务器收到浏览器web请求后,打印一句话console.log("recvreqfrombrowser");
编辑nginx文件vi/usr/local/etcginxginx.confnginx配置如下,配置后需重启nginxnginx-sreloadlocation~.*\.json{roothtml;add_header"Access-Control-Allow-Origin""*";}前端index.html<script>fetch('http://localhost:12
constexpress=require('express')constapp=express()//步骤的拆解constresult=express.static('./views')app.use(result)//再次托管一下样式表的资源目录app.use('/css',express.static('./css'))//托管JS文件目录app.use('/js&#
问题描述:最近在做毕设,express里边的中间件(body-parser)失效,req.body获取不到任何值,req.query能获取到值。一开始加body-parser中间件是有用的,直到昨天加了token之后,body-parser失效。试着把token去掉,无济于事,也不是这个问题,也有说版本对不上的,换了中间件的引入方法,还是没用!!! 后
express官网:---->传送门 expressexpress框架有许多功能,比如路由配置,中间件,对于想配置服务器的前端来说,非常便捷自从node发展之后,基于nodejs的开发框架也不断涌现出来,express就是其中之一,最近简单的写了点express框架的简单的处理请求的demo首先是安装express模块npminstall
目录问题: 操作:Win+S按键,输入“事件查看器”问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll未能加载。返回的数据为错误信息。问题:  操作:Win+S按键,输入“事件查看器” 问题详情:模块DLLC:\ProgramFiles(x86)\IISExpress\aspnetcore.dll
//获取阿里云市场,快递物流记录https://market.aliyun.com/products/56928004/cmapi022273.html?spm=5176.2020520132.101.26.61f97218v18GBF#sku=yuncode1627300000//get_express_log(self::$config['web']['aliyun_AppCode']阿里云市场AppCode,缓存秒数如300秒,'快递公司代