I am learning MVC4. I could display records in a tabular format using foreach
.
Now, I need to display theDescription
of (only) first Topic
object in a label. I need to do it without a foreach
. How can we do it?
VIEW
@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>
}
}
Controller Action
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);
}
Model
namespace MvcSampleApplication.Models
{
public class LabelDisplay
{
public List<Topic> Topics;
}
public class Topic
{
public string Description { get; set; }
public int Code { get; set; }
}
}
REFERENCE