【发布时间】:2017-10-11 21:55:36
【问题描述】:
我有一个名为 GoalTypes 的小型模型,其中包含“跑步、骑自行车、体重……”等内容
public class GoalType
{
public int Id { get; set; }
public string Type { get; set; }
}
我还有一个模型,叫做目标 公开课目标 { 公共 int ID { 获取;放; }
[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>
这会填充下拉列表,但如果我提交它,类型字段将留空
【问题讨论】:
-
因为您创建了名为
listOfGoals的表单控件,但您的模型没有具有该名称的属性(其Type)。您的编辑数据因此始终使用视图模型。请参阅 this Q/A 中的代码以获取典型示例(您使用最坏的可能重载来生成不提供 2 路模型绑定或客户端验证的<select>元素) -
你可能想看看这个answer。
-
当您提交下拉列表时,您提交的是选定值,而不是复杂类型。您可以在提交时检查表单集合吗?
-
-
@CeriWestcott 好吧,听起来好像您需要 javascript 来帮助您解决这个问题。也许我误解了,但听起来好像您需要挂钩下拉列表的 onselect 事件以使用新的选定类型更新表单,也许将部分视图注入到表单中。我不确定...
标签: c# asp.net-mvc