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

    public int Location_Id { get; set; }
    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" })

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

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

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime created_date { get; set; }

    public string created_by { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime? modified_date { get; set; }

    public string modified_by { get; set; }

Related posts

Recent Viewed