MVC 5 基础学习笔记

参考 : 

http://www.cnblogs.com/slark/category/636030.html

http://www.cnblogs.com/hangwei/category/655132.html

 

微软有一些folders的的结构,我们可以参考 follow 

Model,View,Controller 各一个folder 

View/Shared 放一些sharing的view 

View/Shared/_Layout.cshtml 布局

View/_ViewStart.cshtml 每一个view的初始化 

 

Example for _ViewStart.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml"; //每一个View 都是用 _Layout.cshtml 布局, 这个是可以被overwrite掉了.
}

Example for _Layout.cshtml 

复制代码
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />  
    <title>@ViewBag.Title</title>  
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> @*可以直接用 "~/"*@
    @RenderSection("css", required: false) @*RenderSection 可以在子 View 填入内容*@
</head>
<body>
    @RenderBody() @*这个个子 View 内容*@
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    @RenderSection("script", required: false)     
</body>
</html>
复制代码

 

Controller, Model 与 View 之间的沟通

Example Controller

复制代码
using System.Collections.Generic;
using System;
using System.Web.Mvc;
using Project.Models;
using System.Threading.Tasks;

namespace Project.Controllers
{
    [RoutePrefix("")]
    public class HomeController : AsyncController //Async 可以for EF await
    {
        [Route("", Name = "Home")]
        public async Task<ActionResult> Index(string param)
        {
            ViewData["attr"] = "value"; //passing value by 字典 
            ViewBag.attr = "value"; // passing value by dynamic 
            ViewBag.listStr = new List<string> { "a", "b", "c" };
            HomeViewModels homeVM = new HomeViewModels //passing value by ViewModel
            {
                content = "strContent",
                headerViewModels = new HeaderViewModels
                {
                    content = "headerContent"
                }
            };
            return View(homeVM);
        }
    }
}
复制代码

 

Example Model 

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Project.Models
{
    public class HomeViewModels
    {
        public string content { get; set; }
        public HeaderViewModels headerViewModels { get; set; }
    }

    public class HeaderViewModels
    {
        public string content { get; set; }
    }
}
复制代码

如果多的话,可以一个ViewModels 一个 file 

 

Example View

复制代码
@*初始化*@
@{
    ViewBag.title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


@*setup _Layout.cshtml 的 RenderSection*@
@section css {
    <link href="~/Content/Site.css" rel="stylesheet" />
}
@section script {
    <script src="~/Scripts/jquery.validate.js"></script>
}


@*setup ViewModels*@
@model Project.Models.HomeViewModels


<div>
    <p>Home</p>
    @*渲染一个 partial view*@
    @Html.Partial("~/Views/Shared/PartialView/header.cshtml", @Model.headerViewModels);

    <br />
    <p>passing value by 字典 : @ViewData["attr"]</p>
    <p>passing value by dynamic : @ViewBag.attr</p>


    @*looping*@
    @foreach (string str in ViewBag.listStr) @*razor 很聪明的,不需要担心强转的问题,它会搞定*@
    {
        <p>@str</p>
    }
    @for (int i = 0; i < ViewBag.listStr.Count; i++)
    {
        <p>@i</p>
    }

    
    <!--Single Line-->
    @{ var name = "Slark";} @* 有花刮弧的需要分号收尾 *@
    @{ Response.Write("Single Line : Name is" + name + "<br />");}

    <!--Inline-->
    Inline : Today is:@DateTime.Now.ToString("yyyy-MM-dd") <br /> @* Inline 不需要分号收尾 *@
    Inline : Name is @name <br />

    <!--Multi-Line-->
    @{
        var age = 25;
        Response.Write("Multi-Line : Age is " + age + "<br />");
    }

    @*if else*@
    @if (1 > 2)
    {
        Response.Write("1 > 2 <br />");
    }
    else
    {
        Response.Write("1 <= 2 <br />");
    }


    @*create Link*@
    <a href="@Url.RouteUrl("Home",new { param = "param" })">Home</a>
    <br />
    @Html.ActionLink("Home", "Index", "Home", new { param = "param" }, null)
</div> 
复制代码

 

最简单的 form 

View : 

复制代码
@{
    Layout = null;
}
@model ProjectFolderFile.Controllers.ViewModels

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        @using (Html.BeginForm("Index", "Home"))
        {
            @Html.AntiForgeryToken()
            @Html.TextBoxFor(m => m.data.email)
            <input type="submit" value="submit" />
        }
        home 
    </div>
    <script>          
        
    </script>
</body>
</html>
复制代码

Controller 

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ProjectFolderFile.Controllers
{
    public class ViewModels
    { 
        public FromData data { get; set; }
    }
    public class FromData
    {
        public string email { get; set; }
    }
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        { 
            return View(new ViewModels());
        }   
             
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(FromData data)
        {
            return View();
        }
    }
}
复制代码

 

 

razor 解析顺序 :

refer : http://www.cnblogs.com/slark/p/mvc5-ef6-get-started-razor.html

搜寻Razor标记中的C#代码,如果是C#单行或多行代码(有花刮弧的c#),就执行它。如果搜寻到了行内代码(没有花刮弧的),就把这一段代码替换成代码对应的值,

然后服务器会把文件中所有非Razor标记的代码写入要输出的文件。

 

在razor @{} 里面嵌套 html 语法 

refer : http://www.cnblogs.com/slark/p/mvc5-ef6-get-started-razor.html

 

ChildAction & ajax 来调用 partialview 

refer : http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-partialview.html

 

Render section 

refer : http://www.cnblogs.com/hangwei/p/4391058.html

 

传值详解 (view to ctrl (form) , ctrl to view (viewbag等), ctrl & ctrl 等等)

refer : http://www.cnblogs.com/hangwei/p/4466856.html

 

 

Note : 

1.子页面先于布局页面渲染.

 

 

MVC for SPA route 

参考 : http://www.cnblogs.com/usea/p/4211989.html

复制代码
public class SingleRoute : RouteBase
{
    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var data = new RouteData(this, new MvcRouteHandler());
        data.Values.Add("controller", "Home");
        data.Values.Add("action", "Index");
        return data;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        return null;
    }
}
复制代码
复制代码
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("favicon.ico");
        routes.Add(new SingleRoute());

        routes.MapRoute(
            "Admin",
            "Admin/{action}",
            new { controller = "Admin", action = "Index" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );          
    }
}
复制代码

建议如果不做SEO的话可以直接使用 # 就好了,不用搞这些.

 

posted @   兴杰  阅读(253)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 百万级群聊的设计实践
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
点击右上角即可分享
微信分享提示