当前位置:编程学习 > asp >>

ASP.NET MVC 3 直到我膝盖中了一箭【4】小试牛刀

 

1.创建一个ASP.NET MVC 3 项目-->选择Razor视图引擎

2.~/Models/下添加类StudentModels-->重新生成解决方案

3.~/Controllers/下添加控制器StudentController-->添加Index视图

\

4.Global.asax 文件中设置全局 URL 路由默认值 www.zzzyk.com


1             routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // 要忽略的路由的URL模式直接访问.axd文件
2             routes.MapRoute(
3                 "Default", // 路由名称
4                 "{controller}/{action}/{id}", // 带有参数的 URL
5                 new { controller = "Student", action = "Index", id = UrlParameter.Optional } // 参数默认值
6             );
5.未将对象引用设置到对象的实例


 1         public ActionResult Index()
 2         {
 3             return View(GetData());
 4         }
 5
 6         /// <summary>
 7         /// 初始化
 8         /// </summary>
 9         /// <returns></returns>
10         IEnumerable<StudentModels> GetData()
11         {
12             IEnumerable<StudentModels> list = new List<StudentModels>
13                            {
14                                new StudentModels() {ID = 1001, Name = "张三", Age = 20},
15                                new StudentModels() {ID = 1002, Name = "李四", Age = 21},
16                                new StudentModels() {ID = 1003, Name = "王五", Age = 22}
17                            };
18             return list;
19         }
6.详细信息-->添加Details视图


 1         public ActionResult Details(int id)
 2         {
 3             foreach (var student in GetData())
 4             {
 5                 if (student.ID.Equals(id))
 6                 {
 7                     return View(student);
 8                 }
 9             }
10             return View();
11         }
7.创建-->添加Create视图


 1         public ActionResult Create()
 2         {
 3             return View();
 4         }
 5         [HttpPost]
 6         public ActionResult Create(FormCollection collection)
 7         {
 8             try
 9             {
10                 return RedirectToAction("Index");
11             }
12             catch
13             {
14                 return View();
15             }
16         }
8.更新-->添加Edit视图


 1         public ActionResult Edit(int id)
 2         {
 3             return View();
 4         }
 5         [HttpPost]
 6         public ActionResult Edit(int id, FormCollection collecti

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,