Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linq 如何显示selectedlist按id列出的选定值?_Linq_Asp.net Mvc 4_Razor_Selectedvalue_Displayfor - Fatal编程技术网

Linq 如何显示selectedlist按id列出的选定值?

Linq 如何显示selectedlist按id列出的选定值?,linq,asp.net-mvc-4,razor,selectedvalue,displayfor,Linq,Asp.net Mvc 4,Razor,Selectedvalue,Displayfor,我有分类模型 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

我有分类模型

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; }
}
以及在我的控制器中创建的类别列表

List<Category> items = new List<Category>();
它应该根据课程模型的CategoryId值显示类别类型的Name属性

SelectList categories = new SelectList((IEnumerable<MvcImport.Models.Category>)ViewData["categories"], "Id", "Name", item.CategoryId);
但最后一行行不通

不知道如何调用该值。 (我不想显示下拉列表,只显示选定的值)

谢谢

您可以这样尝试:

@Html.DisplayFor(modelItem => categories.First(m => m.Id == item.CategoryId).Name)
或更安全(格式化为可读性):


这一个对我有用:

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

感谢@har07,对于这两个示例,对于行m.Id==item.CategoryId,运算符'=='不能应用于'method group'和'int'类型的操作数。(Category.Id和Course.CategoryId当然都是整数。我的视图类型是
@model IEnumerable
我假设
categories
类型是
IEnumerable
,没有注意到您将其声明为
SelectList
。请尝试:
var categories=(IEnumerable)ViewData[“categories”]
varcategories=(IEnumerable)ViewData[“categories”];
@Html.DisplayFor(categories.Where(m => m.Id == item.CategoryId).FirstOrDefault())
@Html.DisplayFor(modelItem => categories.First(m => m.Id == item.CategoryId).Name)
@Html.DisplayFor(modelItem => categories.Where(m => m.Id == item.CategoryId)
                                        .Select(m => m.Name)
                                        .FirstOrDefault())
@Html.DropDownListFor(x =>item.RequestTypeID, new SelectList(ViewBag.RequestTypes, "Value", "Text", item.RequestTypeID))