asp.net MVC学习笔记

以MVC3为例,了解MVC的运行原理。


从核心的控制器下手,先进行了简单的测试:

        public string Browse(string title)
        {
            string message = HttpUtility.HtmlEncode("store.browse.title=" + title);
            return message;
        }

        public string Test(int id)
        {
            string message = "the id is" + id.ToString();
            return message;
        }

自定义了一个叫Store的controller,里面包含两个方法:Browse和Test

第一个方法接受一个title的字符串参数,结果返回title的内容到页面上。


第二个方法接受一个id的参数,结果也输出id

调用时发现这样的特点:

localhost:xxxx/store/Browse?title=123   这时会输出123到页面上。

localhost:xxxx/store/Test?id=456 和localhost:xxxx/store/Test/456 都会输出456到页面上。

由此可知,

1.controller中的参数会以查询字符串的形式接收url中的参数值。

2.localhost:xxxx/store/Test/456 会以默认路由规则把456当做id的参数进行处理


路由配置如下:

routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );


关于视图。

视图中可以定义一些动态变量,以@开头,在controller中可以给这些动态变量赋值,进行数据传递。

如:

<h2>@ViewBag.Message</h2>
<p>
@ViewBag.Test
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

public ActionResult Index()
{
      ViewBag.Message = "Welcome to ASP.NET MVC!";
      ViewBag.Test = "wangjue test"; 
      ViewData["Test"] = "wangjue test";
      return View();
}

其中,ViewBag.Test 和 ViewData["Test"]这两种赋值的写法是类似的。

为了防止视图中变量的二义性,可以使用()将变量部分括起来。

如果要输出@,需要用两个@来进行转义。


在视图中定义的变量内容为html或脚本时,默认输出的转义后的字符串文本,不会执行脚本,想要执行脚本,可以使用@Html.raw(str)方法。

在razor代码块中混合纯文本的方法:

@if(true){

  <text>this is a text</text>

}

可以采用text标签,标签不会输出,输出的是标签中的文字。

注释使用@*   *@

使用泛型的时候必须用圆括号括起来(因为泛型使用尖括号,引起歧义)

你可能感兴趣的:(asp.net MVC学习笔记)