我正在学习MVC4。我可以使用表格格式显示记录foreach
。
现在,我需要在标签中显示Description
(仅)第一个Topic
对象。我需要在没有foreach
. 我们该怎么做?
看法
@model MvcSampleApplication.Models.LabelDisplay
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
foreach (var item in Model.Topics.Select((model, index) => new { index, model }))
{
<div>@(item.index) --- @item.model.Description---- @item.model.Code</div> <div></div>
}
}
控制器动作
public ActionResult Index()
{
LabelDisplay model = new LabelDisplay();
Topic t = new Topic();
t.Description = "Computer";
t.Code=101;
Topic t3 = new Topic();
t3.Description = "Electrical";
t3.Code = 102;
model.Topics = new List<Topic>();
model.Topics.Add(t);
model.Topics.Add(t3);
return View(model);
}
模型
namespace MvcSampleApplication.Models
{
public class LabelDisplay
{
public List<Topic> Topics;
}
public class Topic
{
public string Description { get; set; }
public int Code { get; set; }
}
}
参考