How to display selectedlist selected value by id?

2.9k views Asked by At

I have Category model

public class Category
{
    //[PlaceHolder("Select file")]
    //[UmbracoRequired("Form.Label.Import.SelectFile")]
    //[UmbracoDisplay("Form.Label.Import.SelectFile")]
    //[Required]
    public int Id { get; set; }

    public string Name { get; set; }
}

and a list of categories created in my controller

List<Category> items = new List<Category>();

Category list should be used in the (strongly typed) view where I have a foreach loop displaying another model Course eg.

        <td>
            @Html.DisplayFor(modelItem => item.Students)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.AdmissionInfo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CategoryId)
        </td>

So instead of

@Html.DisplayFor(modelItem => item.CategoryId)

it should display a Name property of the Category type depending on the CategoryId value of Course model

SelectList categories = new SelectList((IEnumerable<MvcImport.Models.Category>)ViewData["categories"], "Id", "Name", item.CategoryId);

Eg.

@Html.DisplayFor(categories.Where(m => m.Id == item.CategoryId).FirstOrDefault())

But that last line does not work.

Not sure how to call just the value. (I DO NOT want to display a dropdown, just the selected value)

Thanks

2

There are 2 answers

3
har07 On BEST ANSWER

You can try this way :

@Html.DisplayFor(modelItem => categories.First(m => m.Id == item.CategoryId).Name)

or more safely (formatted for readability) :

@Html.DisplayFor(modelItem => categories.Where(m => m.Id == item.CategoryId)
                                        .Select(m => m.Name)
                                        .FirstOrDefault())
0
InGeek On

This one worked for me:

@Html.DropDownListFor(x =>item.RequestTypeID, new SelectList(ViewBag.RequestTypes, "Value", "Text", item.RequestTypeID))