1

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

nickornotto
  • 1,946
  • 4
  • 36
  • 68

2 Answers2

1

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())
har07
  • 88,338
  • 12
  • 84
  • 137
  • Thanks @har07 I'm getting `Operator '==' cannot be applied to operands of type 'method group' and 'int'` for the line m.Id == item.CategoryId for both examples (both Category.Id and Course.CategoryId are integers of course. My view is of type `@model IEnumerable` – nickornotto Aug 07 '14 at 11:22
  • I assumed that `categories` is of type `IEnumerable`, didn't notice that you declared it as `SelectList`. Try : `var categories = (IEnumerable) ViewData["categories"];` – har07 Aug 07 '14 at 14:16
  • Fantastic @har07! This works `var categories = (IEnumerable)ViewData["categories"];` with `@Html.DisplayFor(modelItem => categories.First(m => m.Id == item.CategoryId).Name)` – nickornotto Aug 07 '14 at 15:40
0

This one worked for me:

@Html.DropDownListFor(x =>item.RequestTypeID, new SelectList(ViewBag.RequestTypes, "Value", "Text", item.RequestTypeID))
InGeek
  • 2,532
  • 2
  • 26
  • 36