我是Entity Framework / MVC的新手,需要知道如何修改Visual Studio自动生成的下拉菜单。我想它应该很简单,但我无法弄明白。我使用了数据库优先方法,并在我的数据库中有以下两个表:
public partial class RestaurantRating
{
public int RestaurantRatingId { get; set; }
public int RestaurantRatingScore { get; set; }
}
public partial class RestaurantType
{
public int RestaurantTypeId { get; set; }
public string RestaurantTypeDesc { get; set; }
}
我删除了额外的细节,但基本上其中一个将存储餐馆评级(评级为整数),另一个将存储餐馆类型(他们服务的食物类型)。两者之间唯一真正的区别是评级是一个整数,它们的类型描述是一个字符串。
Visual Studio自动生成的代码,用于这些表和其他表的CRUD操作。 Create.cshtml中这两个表的HTML代码如下:
<div class="form-group">
@Html.LabelFor(model => model.RetaurantTypeId, "RetaurantTypeId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("RetaurantTypeId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.RestaurantTypeId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.RestaurantRatingId, "RestaurantRatingId", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("RestaurantRatingId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
</div>
</div>
控制器中Create Action结果中这两个表的ViewBag信息如下:
ViewBag.RestaurantRatingId = new SelectList(db.RestaurantRating, "RestaurantRatingId", "RestaurantRatingId");
ViewBag.RestaurantTypeId = new SelectList(db.RestaurantType, "RestaurantTypeId", "RestaurantTypeDesc");
问题和预期结果如下:
RestaurantType的下拉菜单按预期工作。它只是将不同类型加载到下拉菜单中,并允许用户选择其中一种。但是,RestaurantRating将加载RatingIds而不是描述,这是我需要的。我尝试过更换viewbag但没有成功。
HTML代码会自动选择下拉菜单的第一个值,但可以为这些字段将NULL值保存到数据库中。如何为上面的下拉菜单添加一个空的默认值,这样如果用户选择空值(或者不触摸下拉菜单),NULL值将被推送到数据库?
非常感谢任何帮助。我很乐意提供任何其他代码/信息。非常感谢你!
答案 0 :(得分:1)
您只需要在下拉列表中添加选项标签,如下所示: -
@Html.DropDownList("RetaurantTypeId", null,"optionLable goes Here", htmlAttributes: new { @class = "form-control" })
并确保在另一方面将它绑定到可为空的模型属性,因此模型绑定器将能够将模型属性值设置为Null。 希望这能回答你的问题。