我的广告资源跟踪计划有一个名为INV_Assets
的主要类。这包括多个子表的[ForeignKey]
个字段,包括INV_Locations
:
[Required]
public int Location_Id { get; set; }
[ForeignKey("Location_Id")]
public virtual INV_Locations Location { get; set; }
现在,在Create()/Edit()
INV_Assets
ViewData[]
行动方法中,我填写SelectList
元素,其中INV_Locations
将在视图上使用(此选择列表合并2将我的ViewData["Location_Id"] = new SelectList((from l in db.INV_Locations.ToList() select new { location_room = l.location_dept + "|" + l.location_room }), "location_room", "location_room");
字段放入下拉列表中 - 例如[location_dept] | [location_room] - [IT] | [服务器]):
ViewData[]
然后在我的视图中,我使用SelectList/DropDownListFor
元素填充 <span class="control-label col-md-2">Location:</span>
<div class="col-md-4">
@Html.DropDownListFor(model => model.Location_Id, (SelectList)ViewData["Location_List"], htmlAttributes: new { @class = "form-control dropdown", @id = "selectLocation" })
@Html.ValidationMessageFor(model => model.Location_Id, "", new { @class = "text-danger" })
</div>
:
[IT]|[Server] => [IT]|[Cubicle]
正如我想要的那样正确地填充我的DropDownList,但在我做出选择之后(无论是为Edit()更改选择[<<< SELECT >>>] => [IT]|[Server]
还是为Create()更改"The field Location_Id must be a number."
)一旦焦点移开我获取验证/错误消息Id
具有更多经验的人是否可以权衡我需要修改的内容以保持此验证,但要正确实施?我可能会在DropDown中直观地组合字段[location_dept] | [location_room],但INV_Location
的{{1}}应该是相同的吗?
如果下面有帮助,我的INV_Locations
模型:
public class INV_Locations
{
public override string ToString()
{
return this.location_dept + "|" + this.location_room;
}
public int Id { get; set; }
[Display]
[Required(ErrorMessage = "Please enter a Location Dept.")]
public string location_dept { get; set; }
[Required(ErrorMessage = "Please enter a Room.")]
public string location_room { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime created_date { get; set; }
[Required]
public string created_by { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? modified_date { get; set; }
public string modified_by { get; set; }
}
答案 0 :(得分:1)
您的Location_Id
字符串
select new { location_room = l.location_dept + "|" + l.location_room }
你的模型希望它是一个int。