Home > database >  how to configure dropdownlist to return the Title and not id back to the database
how to configure dropdownlist to return the Title and not id back to the database

Time:08-10

I have an asp.net mvc using entity framework web app. A specific table in the app has a text column we want to force users to select entries from a dropdown to avoid spelling issues. There are only two selections, Buy Item and Raw Components. We don't want to go through the trouble of creating an actual table and then relate that table with the original. When creating a new record or editing an existing record I would like to have the selected Text and not the selected ID saved in the record. The reason for this is there are many records in the table already AND a report deck associated with the table that would all have to be updated if the ID was saved back to the record. In the examples I've included below, you see I've used the ViewBag method although the Model method (for me) has the same issues.

To start I created a class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProdMan4.Models
{
public class ItemTypes
{
    public int Id { get; set; }
    public string Title { get; set; }
}

}

Added the following to the controller for this table...

private List<ItemTypes> GetITs()
    {
        var itemtypes = new List<ItemTypes>();
        itemtypes.Add(new ItemTypes() {Id = 1, Title = "Buy Item" });
        itemtypes.Add(new ItemTypes() {Id = 2, Title = "Raw Components" });

        return itemtypes;
        
    }

 public ActionResult Create()
    {
        ViewBag.ItemTypesSelectList = new SelectList(GetITs(),"Id", "Title");
        return View();
    }

Then Added the dropdown on the Create View as follows...

<div >
        @Html.LabelFor(model => model.ItemType, htmlAttributes: new { @class = "control-label col-md-2" })
        <div >
            @Html.DropDownList("Title", ViewBag.ItemTypesSelectList as SelectList, "Select Type", new { @class = "form-control" })               
            @Html.ValidationMessageFor(model => model.ItemType, "", new { @class = "text-danger" })
        </div>
    </div>

I have two issues.

  1. I can create a new item but it saves the ID to the SQL table
  2. The edit view, while setup just like the create view for this column, throws the following error.

System.InvalidOperationException: 'The ViewData item that has the key 'Id' is of type 'System.Int32' but must be of type 'IEnumerable'.'

At this point I'm a bit lost. Any direction would be appreciated.

CodePudding user response:

Use Html.DropDownListFor like this

@Html.DropDownListFor(m=>m.ItemType, ViewBag.ItemTypesSelectList as SelectList,"--- select type --- ",new { @class = "form-control" })

  • Related