標籤:傳值
在MVC中,傳值是一個很重要的內容之一。前面的部落格中,我們瞭解了如何從Controller中向View傳遞單個的變數值以及從View向Controller的反向傳遞。
這次我們來看看,如何把一個List集合進行傳遞。
首先,我們先在Controller中建立一個List:
public ActionResult Index() { ViewData["QuestionId"] = Request.QueryString["QuestionID"];//從頁面的地址欄中擷取QuestionID //根據試題ID查詢題庫資訊 List<ExamQuestionBankEntity> QuestionBankList = new List<ExamQuestionBankEntity>(); ExamQuestionBankEntity enQuestionBank = new ExamQuestionBankEntity();//定義新實體 examQuestionBankService = ExamServiceFactory.GetQuestionBankService();//擷取服務 List<string> questionId = new List<string>(); questionId.Add(ViewData["QuestionId"].ToString());//擷取試題ID QuestionBankList = examQuestionBankService.QueryQuestionInfoByQuestionGUIdList(questionId);//執行查詢試題方法 ViewData["QuestionBankList"] = QuestionBankList;//傳到介面用的,顯示具體一道題的試題資訊 return View(); }
在View中要想顯示集合中的資訊,首先要引用實體集合中的“實體”,我這裡的是ViewModel。之後要通過一個迴圈來進行參數傳遞。
在View中:
@using ITOO.Exam.ViewModel ;<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>樣本</title></head><body> <div id="mainBody"> <div id="ContentAreas"> <div class="easyui-panel" title="判分" style="height: 300px;"> @foreach (ExamQuestionBankEntity a in ViewData["QuestionBankList"] as List<ExamQuestionBankEntity>) { @*載入選中的題的資訊,包括大小題號、題幹內容、標準答案、分值*@ <label for="lblParentQuestionTopic" style="display: block; margin-top: 5px;">試題題幹:</label> <label for="lblTopic" style="display: block; margin-top: 5px;">@a.ParentQuestionId、@[email protected]*(共x小題,共y分)*@</label> <hr size="1" width="1200" color="black" align="left"/> <label for="lblLittleQuestionTopic" style="display: block; margin-top: 5px;">@a.LittleQuestionId、</label> <label for="lblLittleQuestion" style="display: block; margin-top: 5px;">@a.MainQuestion</label> <div style="margin-top: 5px;font:bold"> <label id="lblMainContentTopic">標準分數:</label> <label for="lblScore">@a.Score</label> </div> <div style="margin-top: 5px;"> <label id="txtCorrectAnswerTopic">參考答案:</label> <label for="lblCorrectAnswer" >@a.CorrectAnswer</label> </div> <div style="margin-top: 5px;"> <label id="txtQuestionAnalysis">試題分析:</label> <label for="lblCorrectAnswer" >@a.Analysis</label> </div> } </div> </div> </div> </body>
這裡我是把具體的list中的各個值通過迴圈的方式顯示出來的。嚴格來說,這並不是一種很好的方法,因為我的list中保證了只有一條資料,所以list其實不是很合適。
這種方法比較適合應用在表格中,通過迴圈逐條顯示資料,這裡就不展示代碼了。
其實還有其他方法通過Controller向View中傳list。我所知道和用過的另一種方法比較複雜,對ViewModel的操作比較複雜,沒有使用迴圈,但主要是用來顯示表格資料的。具體就不在這裡寫了,大家有興趣的可以上網查一下。
關於MVC 傳值的其他內容,以後還會有專題總結,敬請期待~
MVC傳值--從Controller想View傳遞List集合