asp.net mvc - Displaying one object value (from a collection) in a label -


i learning mvc4. display records in tabular format using foreach.

now, need display thedescription of (only) first topic object in label. need without foreach. how can 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

  1. iterate through collection , print index , item in razor

i need display thedescription of (only) first topic object in label

unless totally misunderstood you, selecting first item (only) in view like:

@if (model.topics.any()) {     @html.displayfor(x => x.topics.first().description) } 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -