NULL
NULL

Reputation: 1589

multiple select list c# mvc

I am trying to create a multiple select from a single select drop down menu. my model originally had:

public int country_id { get; set; }

and my view had:

 @Html.DropDownList("country_id", String.Empty) 

to change it to multiple select i changed my model to:

public List<Country> country_id { get; set; }

and my view to:

@Html.ListBoxFor(model => model.country_id, ViewBag.ActionsList as MultiSelectList, new { @class = "multiselect", @style = "width: 450px;height:200px" })

the problem i am having is updating my databse using migration since the i am changing int to list, however, it keeps saying

"Cannot drop the index 'dbo.People.IX_country_id', because it does not exist or you do not have permission."

I do have permission so I am not sure if I am missing something?

My list of countries is coming straight from the country database.

thanks for your inputs.

Upvotes: 1

Views: 5835

Answers (1)

markpsmith
markpsmith

Reputation: 4918

You need to populate a selectlist in the controller & pass it to the view, something like this:

var countries = from d in db.Countries
                        select new
                        {
                            Id = d.Id,
                            Name = d.Name
                        };
// I'd pass this in a model, but use ViewBag if that's what you're familiar with
ViewBag.ActionsList =  new SelectList(countries , "Id", "Name");

And in the View:

@Html.DropDownListFor(model => model.country_id, ViewBag.ActionsList)

UPDATE:

You should use a ViewModel for this:

public class CountryList
{
    // this may have to be a List<SelectListItems> to work with MultiSelectList - check.
    public SelectList Countries{ get; set; }
    public List<int> SelectedCountryIds { get; set; }
}

In the controller:

var model = new CountryList
{
    SelectList = //assign the selectlist created earlier
}
return View(model);

In the View:

@Html.ListBoxFor(m => m.SelectedCountryIds, new MultiSelectList(@Model.Countries, "Id", "Name", @Model.SelectedCountryIds))

Upvotes: 1

Related Questions