在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、@a.QuestionTypeCode@*(共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 传值的其他内容,以后还会有专题总结,敬请期待~