c# - 下拉列表中的空值(for)

标签 c# asp.net-mvc razor

最后一天,我在 Razor View 中看到了这一点

@Html.DropDownListFor(x => x.FoodId,null, htmlAttributes: new { @class = "form-control" })
// and (just another alternative)
@Html.DropDownList("FoodId", null, htmlAttributes: new { @class = "form-control" })

我想知道列表中的数据发生了什么,数据填充发生在何时何地?两条线有什么区别?以及下拉列表如何填充数据(因为代码执行中有数据)

抱歉我的英语不好

更新#1

型号: Food.cs 和 User.cs

public partial class Food
{
    public Food()
    {
        this.User = new HashSet<User>();
    }

    public System.Guid Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<User> User { get; set; }
}
//
public partial class User
{
    public System.Guid Id { get; set; }
    public string Name { get; set; }
    public Nullable<System.Guid> FoodId { get; set; }

    public virtual Food Food { get; set; }
}

Controller (仅操作)

    public ActionResult Create()
    {
        ViewBag.FoodId = new SelectList(db.FoodSet, "Id", "Name");
        return View();
    }

天哪,谢谢,我现在很愚蠢:)

答案:充满 ViewBag.FoodId

最佳答案

当将 null 值传递给第二个参数时,它会自动在 ViewBag 中查找,即使没有 JavaScript 且已清除缓存> 与下拉菜单同名的键,否则启动异常。 就我而言,传递了 null 并检查了 ViewBag 并找到了一个 key

关于c# - 下拉列表中的空值(for),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29987288/

相关文章:

asp.net-mvc - 组织站点管理部分 - 用户部分 MVC

c# - 是否可以在 Asp.NET razor 代码中嵌套 foreach 循环?

c# - 如何使用@Html.Raw、ASP.NET、Razor @Helper

c# - Asp.net Core 迁移,后操作不再有效

c# - C# WPF 中的内存泄漏

c# - 要在 Entity Framework 中编辑多对多关系,为什么必须先清除集合?

c# - EPPlus AddPicture 导致 Excel 2007 文件损坏

C# Transpose() 方法转置 excel 表中的行和列

c# - 在 Razor-4 View 中访问模型属性

asp.net-mvc - ASP.net MVC : Getting Required Roles for Login?