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

2019-09-08 01:52发布

My Inventory Tracking program has a main class called INV_Assets. This includes [ForeignKey] fields for several child tables including INV_Locations:

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

Now then, on my Create()/Edit() action methods for INV_Assets I am filling a ViewData[] element with a SelectList to be used on the View (this Select List combines 2 of my INV_Locations fields into one within the dropdown - ex. [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");

Then on my View I used the ViewData[] element to fill a 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>

My DropDownList is correctly being filled as I intend, but after I make a Selection (be it changing the selection [IT]|[Server] => [IT]|[Cubicle] for Edit() or [<<< SELECT >>>] => [IT]|[Server] for Create()) once focus shifts away I get the Validation/Error message "The field Location_Id must be a number."

Can someone with more experience weigh in with what I need to modify to keep this validation in place, but to be properly implemented? I may be combining the fields [location_dept]|[location_room] visually in the DropDown, but the Id for the INV_Location should be the same?

If it helps below is my INV_Locations Model:

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; }
}

1条回答
男人必须洒脱
2楼-- · 2019-09-08 02:25

It appears you are population your dropdown for Location_Id with strings

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

And your model expects it to be an int.

查看更多
登录 后发表回答