Search code examples
asp.net-mvcviewbagselectlistselectlistitem

Get single values from ViewBag SelectList


This question should be rather simple.

I have the following code:

            ViewBag.SenderID = new SelectList(db.Senders, "SenderID", "SenderContactName", survey.SenderID);

            //Attempts
            string _SenderContactName = ViewBag.SenderID.ToString();
            string _senderContactName = survey.SenderID.ToString();

Results:

_SenderContactname = System.Web.MVC.SelectList

_senderContactName = "1"

What I want the result to be is the SenderContactName from the VewBag, in the form of a string. I Believe my second attempt is closer to the working code. But I can´t seem to figure out how to fix it on my own.


Solution

  • In your case you should do:

    string _senderContactName = db.Senders
                                .FirstOrDefault(x => x.SenderID == survey.SenderID)
                                .SenderContactName;