C# 在MVC中创建一个DropDownList,它仍然填充支持它的模型
我有一个称为GoalTypes的小模型,其中包含诸如“跑步、骑自行车、体重……等”之类的内容 我还有一个叫做目标的模型 公共阶级目标 { 公共int Id{get;set;}C# 在MVC中创建一个DropDownList,它仍然填充支持它的模型,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个称为GoalTypes的小模型,其中包含诸如“跑步、骑自行车、体重……等”之类的内容 我还有一个叫做目标的模型 公共阶级目标 { 公共int Id{get;set;} [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] public DateTime StartDate { get; set; } [DataType(D
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? EndDate { get; set; }
public string Type { get; set; }
public double Level { get; set; }
}
类型字段将由GoalTypes中的类型字段填充。
在我的目标控制器中,我完成了:
public ActionResult Create()
{
ViewBag.listOfGoals = new SelectList(db.GoalTypes, "Id", "Type");
return View();
}
在我看来
<div class="form-group">
@Html.LabelFor(model => model.Type, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("listOfGoals", "Select a Goal")
@Html.ValidationMessageFor(model => model.Type, "", new { @class = "text-danger" })
</div>
</div>
@LabelFor(model=>model.Type,htmlAttributes:new{@class=“controllabel col-md-2”})
@DropDownList(“目标列表”、“选择目标”)
@Html.ValidationMessageFor(model=>model.Type,“,new{@class=“text danger”})
这将填充下拉列表,但如果我提交它,类型字段将留空您必须将@ViewBag传递给@Html.DropDownList,如下所示:
@Html.DropDownList("listOfGoals", ViewBag.listOfGoals)
或创建辅助对象:
public class MyHelpers{
public static SelectList DropDownListGoalTypes(int? selected) {
var list = db.GoalType.ToList();
return new SelectList(list, "Id", "Type", selected);
}
}
视图:
@Html.DropDownList(“目标列表”、“选择目标”)
生成如下选择元素:
<select name="listOfGoals" id="listOfGoals"></select>
或
因为您正在创建名为
listOfGoals
的表单控件,但您的模型没有具有该名称的属性(其类型
)。编辑数据时,请始终使用视图模型。请参阅中的代码以了解典型示例(您使用最坏的重载生成不提供双向模型绑定或客户端验证的
元素),您可能希望查看此示例。提交dropdownlist时,您提交的是所选值,而不是复杂类型。你能在提交时检查formcollection吗?@gardarvalur我很乐意提交所选的值,如果我只是掌握了这些东西,那么也许以后我会编辑它以提交复杂类型。@CeriWestcott嗯,听起来好像你需要javascript来帮你解决这个问题。也许我被误解了,但听起来好像您需要钩住dropdownlist的onselect事件,以使用新的选定类型更新表单,可能是将partialview注入表单。我不确定…如果ViewBag
中提供了listOfGoals
,则没有必要这样做。在这种情况下,视图似乎不是类型化视图。即使使用第二个参数,它也不是强类型视图。我想你误解了我的意思。如果在控制器中填充ViewBag.listOfGoals
,并且视图中有@Html.DropDownList(“listOfGoals”)
,它将按原样工作。无需按照您在答案第一部分中的建议,明确添加(SelectList)ViewBag.listOfGoals
。我明白了,不需要强制执行。我不知道为什么在给出答案后,它会被否决,并且上面的代码可以工作。
@Html.DropDownListFor(x => x.Id, MyHelpers.DropDownListGoalTypes(Model.Id))
<select name="listOfGoals" id="listOfGoals"></select>
@Html.DropDownListFor(model => model.Type, (IEnumerable<SelectListItem>)ViewBag.listOfGoals, "Select a Goal")
@Html.DropDownListFor("Type", (IEnumerable<SelectListItem>)ViewBag.listOfGoals, "Select a Goal")
public int Type { get; set; }