asp.net mvc 3 razor get one element from IEnumerab

2019-04-05 04:58发布

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

3条回答
男人必须洒脱
2楼-- · 2019-04-05 05:33
@foreach(var model in Model)
{
    @model.ToUserID
}
查看更多
小情绪 Triste *
3楼-- · 2019-04-05 05:35

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());
查看更多
贼婆χ
4楼-- · 2019-04-05 05:39

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!)

查看更多
登录 后发表回答