Asp.Net MVC系列--基礎篇(3)

mybwu_com發表於2014-03-05

這一節,介紹一下如何用已經建立好的Domain Model 層,來構建一個簡單的demo

1.右鍵controller->新增一個controller 命名為StudentClassController

完成以下Action:

 public class StudentClassController :Controller
{
//先傳進來介面,後面會用structuremap來做DI
       private IStudentContext _studentContext;
       public StudentClassController(IStudentContext context)
       {
           _studentContext = context;
       }
 
//用於顯示一個class列表
       public ActionResult ClassList()
       {
           var model = _studentContext.StudentClasseList;
           return View("ClassList", model);
       }
 
//用於顯示class詳細內容,學生列表
       public ActionResult ClassDetails(int classId)
       {
           var model = _studentContext.StudentClasseList.First(c => c.Id ==classId);
           var students = _studentContext.StudentList.Where(s => s.ClassId ==classId);
 
           model.Students = students.Any() ? students.ToList() : newList<Student>();
 
           return View("ClassStudentList", model);
       }
 
//指向建立studentview,傳遞classId過去
       public ActionResult GotoCreateStudent(int classId)
       {
           return View("CreateStudent", new Student {ClassId = classId});
       }
 
 
//建立一個student,建立成功並返回到class 詳細資訊頁面
       [HttpPost]
       public ActionResult CreateStudent(Student student)
       {
           if (ModelState.IsValid)
           {
               _studentContext.Students.Add(student);
                _studentContext.Save();
 
                var model =_studentContext.StudentClasses.Find(student.ClassId);
                model.Students =_studentContext.Students.Where(s => s.ClassId == student.ClassId).ToList();
 
                returnView("ClassStudentList",model);   
            }
           return View("CreateStudent", student);
       }


接下來,新增三個View

1.右鍵Views->新增資料夾->StudentClass

2.右鍵StudentClass->新增View->Class List View


View程式碼:

@modelIEnumerable<eStudentDomain.Entity.StudentClass>
 
@{
   Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
   <meta name="viewport"content="width=device-width" />
   <title>ClassList</title>
</head>
<body>
  
   <table>
       <tr>
           <th>
                @Html.DisplayNameFor(model=> model.Name)
           </th>
           <th></th>
       </tr>
   
   @foreach (var item in Model) {
       <tr>
           <td>
                @Html.DisplayFor(modelItem=> item.Name)
           </td>
           <td>
               @Html.ActionLink("Details", "ClassDetails","StudentClass", new { classId = item.Id }, null);
 
           </td>
       </tr>
    }
   
   </table>
</body>
</html>


程式碼說明:使用此View的合約,需要傳遞一個IEumerable<StudentClass> , 這個View會迴圈輸出班級列表表格,最後一個ActionLink指向StudentClassController的ClassDetails Action,傳遞引數classId。

這個Action會拿到ClassId取Class資訊,放入student List,傳遞並指向到ClassStudentList View。

2.右鍵Views->StudentClass,建立View-> ClassStudentList

View 程式碼:

@model eStudentDomain.Entity.StudentClass
 
@{
   Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
   <meta name="viewport"content="width=device-width" />
   <title>ClassStudentList</title>
</head>
<body>
   
   <table>
       <tr>
           <th>
                @Html.DisplayNameFor(model=> model.Name)
           </th>
           <th></th>
       </tr>
 
       @foreach (var item in Model.Students) {
           <tr>
                <td>
                    @Html.DisplayFor(modelItem=> item.Name)
                </td>
           </tr>
       }
   
   
   </table>
   <p>
       @Html.ActionLink("Add Student", "GotoCreateStudent","StudentClass", new { classId = Model.Id },null)
       
   </p>
   <p>
       @Html.ActionLink("Back", "ClassList","StudentClass", null, null);
   </p>
</body>
</html>


程式碼說明:此View接收一個StudentClass類作為引數,並且迴圈輸出了class裡面的student列表。最後ActionLink指向了StudentClass controller的GoToCreateStudent的Action,傳遞引數 classId。這個Action拿到ClassId傳遞指向CreateStudent View。

3.右鍵StudentClass->新增View->新增CreateStudent View

@using eStudentDomain.Entity
@model eStudentDomain.Entity.Student
 
@{
   Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
   <meta name="viewport"content="width=device-width" />
   <title>CreateStudent</title>
</head>
<body>
   <scriptsrc="~/Scripts/jquery-1.7.1.min.js"></script>
   <scriptsrc="~/Scripts/jquery.validate.min.js"></script>
   <scriptsrc="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
   
    @using(Html.BeginForm("CreateStudent","StudentClass",FormMethod.Post)){
       @Html.ValidationSummary(true)
   
        <fieldset>
           @Html.HiddenFor(model => model.ClassId);
           <legend>Student</legend>
   
           <div class="editor-label">
                @Html.LabelFor(model =>model.Name)
           </div>
           <div class="editor-field">
                @Html.EditorFor(model =>model.Name)
               @Html.ValidationMessageFor(model => model.Name)
           </div>
 
           <div class="editor-label">
                @Html.LabelFor(model =>model.JoinDate)
           </div>
           <div class="editor-field">
                @Html.EditorFor(model =>model.JoinDate)
               @Html.ValidationMessageFor(model => model.JoinDate)
           </div>
   
           <div class="editor-label">
                @Html.LabelFor(model =>model.GraduateDate)
           </div>
           <div class="editor-field">
                @Html.EditorFor(model =>model.GraduateDate)
               @Html.ValidationMessageFor(model => model.GraduateDate)
            </div>
   
           <p>
                <inputtype="submit" value="CreateStudent" />
           </p>
       </fieldset>
    }
   
   <div>
       @Html.ActionLink("Back to List", "ClassDetails","StudentClass", new { classId = Model.ClassId }, null);
   </div>
</body>
</html>


程式碼說明:

這個View接收Student實體。

@using(Html.BeginForm("CreateStudent","StudentClass",FormMethod.Post)){


表明,這個表單指向StudentClass controller 的CreateStudent Action,表單提交方式為POST。

在CreateStudent Action 裡,接收一個Student物件,並限制HTTP請求方式為POST。這裡傳輸序列化協議為JSON,但是mvc已經把這個過程做好了,表單提交後,Model將被序列化為JSON以POST請求提交到伺服器,Action接收到的,已經是反序列化好的Student物件了。Action建立物件,返回ClassStudentList View,給一個classId。

最後,放一個ActionLink,返回StudentClass Controller的ClassDetails Action,給一個classId,這個Action裡,將取出classId內的students,指向StudentClassList View,給一個StudentClass物件。

View和Controller的程式碼都做完了,還有DI沒做,我們去package manager,安裝 structure map。

會看到生成好的 IoC.cs 檔案,開啟

新增一行(紅色)程式碼即可。

namespaceeStudentManager.DependencyResolution {
   public static class IoC {
       public static IContainer Initialize() {
           ObjectFactory.Initialize(x =>
                        {
                            x.Scan(scan =>
                                    {
                                       scan.TheCallingAssembly();
                                       scan.WithDefaultConventions();
                                    });
                           x.For<IStudentContext>().Use<eStudentDbContext>();
                            //                x.For<IExample>().Use<Example>();
                        });
           return ObjectFactory.Container;
       }
    }
}


最後,我們可以選擇配置一下路由,預設指向ClassList :


好了,這個例子就完成了。執行一下:

Class List :

Student Class


點選Add Student,進入CreateStudent


點選CreateStudent,回到了Class Student:




相關文章