由于验证无法创建 ()/编辑 () 记录?

Cannot Create()/Edit() record due to Validation?

我的库存跟踪程序有一个名为 INV_Assets 的主要 class。这包括几个子表的 [ForeignKey] 字段,包括 INV_Locations:

    [Required]
    public int Location_Id { get; set; }
    [ForeignKey("Location_Id")]
    public virtual INV_Locations Location { get; set; }

现在,在 INV_AssetsCreate()/Edit() 操作方法中,我正在用要在视图上使用的 SelectList 填充 ViewData[] 元素(此 Select 列表在下拉列表中将我的 INV_Locations 字段中的 2 个合并为一个 - 例如 [location_dept]|[location_room] - [IT]|[Server]):

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");

然后在我的视图中,我使用 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>

我的 DropDownList 已按照我的意图正确填充,但是在我创建 Selection 之后(无论是更改选择 [IT]|[Server] => [IT]|[Cubicle] for Edit() 还是 [<<< SELECT >>>] => [IT]|[Server] for Create( )) 一旦焦点移开,我就会收到 Validation/Error 消息 "The field Location_Id must be a number."

有更多经验的人可以权衡一下我需要修改什么以保持此验证到位,但要正确实施吗?我可能会在 DropDown 中可视化地组合字段 [location_dept]|[location_room],但是 INV_LocationId 应该相同吗?

如果有帮助,下面是我的 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; }
}

您似乎在 Location_Id 的下拉列表中填充字符串

select new { location_room = l.location_dept + "|" + l.location_room }

并且您的模型期望它是一个整数。