1. Create an ASP. net mvc 3 project --> select Razor view Engine
2 .~ /Models/Add the class StudentModels --> regenerate the solution
3 .~ /Controllers/Add the Controller StudentController --> Add the Index View
4. Set the default value of Global URL routing in the Global. asax file to www.2cto.com.
1 routes. IgnoreRoute ("{resource}. axd/{* pathInfo}"); // directly access the. axd file in the URL mode of the route to be ignored
2 routes. MapRoute (
3 "Default", // route name
4 "{controller}/{action}/{id}", // URL with Parameters
5 new {controller = "Student", action = "Index", id = UrlParameter. Optional} // default value of the Parameter
6 );
5. The object reference is not set to the instance of the object.
1 public ActionResult Index ()
2 {
3 return View (GetData ());
4}
5
6 /// <summary>
7 // Initialization
8 /// </summary>
9 /// <returns> </returns>
10 IEnumerable <StudentModels> GetData ()
11 {
12 IEnumerable <StudentModels> list = new List <StudentModels>
13 {
14 new StudentModels () {ID = 1001, Name = "James", Age = 20 },
15 new StudentModels () {ID = 1002, Name = "", Age = 21 },
16 new StudentModels () {ID = 1003, Name = "Wang Wu", Age = 22}
17 };
18 return list;
19}
6. Details --> Add the Details View
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 --> Add Create View
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. Update --> Add Edit View
1 public ActionResult Edit (int id)
2 {
3 return View ();
4}
5 [HttpPost]
6 public ActionResult Edit (int id, FormCollection collection)
7 {
8 try
9 {
10 return RedirectToAction ("Index ");
11}
12 catch
13 {
14 return View ();
15}
16}
9. Delete --> Add Delete View
1 public ActionResult Delete (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}
12 [HttpPost]
13 public ActionResult Delete (int id, FormCollection collection)
14 {
15 try
16 {
17 // TODO: Add delete logic here
18
19 return RedirectToAction ("Index ");
20}
21 catch
22 {
23 return View ();
24}
25}
10. Start execution
Author Yixin yiyu