15

I my view model(LIST) looks like this:

public class ConversationModel 
    {
        public int ID { get; set; }
        public string Body { get; set; }
        public DateTime Datetime { get; set; }
        public string Username { get; set; }
        public string ImgUrl { get; set; }
        public string ToUserID{ get; set; }
    }

this is my view

@model IEnumerable<NGGmvc.Models.ConversationModel>

how i can get ToUserID on current postion? something like this

@Model[0].ToUserID

Thanks

Irakli Lekishvili
  • 33,492
  • 33
  • 111
  • 169

3 Answers3

20

You should be able to do:

@Model.First().ToUserID

Note, you may want to check whether there are any items in the enumerable first as if there aren't, then First() will return null

(Note, because you had @Model[0] in your question, I assume you are specifically trying to get the first value. I may have the wrong end of the stick, in which case Jakub's answer should sort you out!)

AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
  • AdTheDev, where do I gain MVC Model Jedi Knowledge. Your answer resolved my issue. On to the next problem. – Moojjoo May 22 '15 at 19:44
  • 1
    Note that `@Model.First()` will throw an exception if the data is not found. Another option is to use `@Model.FirstOrDefault()` which will return null if data is not found, if there was a chance that the data wouldn't exist for example. – jakobinn Feb 08 '19 at 13:32
3

You should be able to use the following:

@Model.First().ToUserID

However, if your model will only ever reference the first element of the enumeration in the view, I would recommend that you only pass that element to the view.

For example:

@model ConversationModel

@Model.ToUserID

And in the controller only pass the first element that is required:

List<ConversationModel> conversationList = //your conversation model initialisation code
return View(conversationList.First());
Dangerous
  • 4,818
  • 3
  • 33
  • 48
  • 1
    I've just seen the other answers and from this I am now questioning what it is you ask for? Is it the first element of the enumerable type that you require or every element? – Dangerous May 15 '12 at 10:24
1
@foreach(var model in Model)
{
    @model.ToUserID
}
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126