简体   繁体   中英

how to store Multiple selction / Dropdownlist in C#

i'm new in MVC and C# and for a project im trying to let the user to multiselect cities from a list and store it to the DB later. Ive read couple of a few posts regarding this but couldnt figure out how to fix mine. I can store all the other items of my form:

@using ( Html.BeginForm( "AddProjectInfo", "Insert", FormMethod.Post, new {
        enctype = "multipart/form-data"
        @id = "insertform", @class = "form-horizontal col-md-4 col-md-offset-4"
    } ) )

but for city it only stores the first selected item not all. can you please help me to fix this?

Here is my view:

<div class="form-group">
        <label class="col-sm-3 col-form-label text-left">City * </label>
        <div class="col-sm-9">
            @Html.DropDownList(
             "City",
             new SelectListItem[] {
                    new SelectListItem {
                        Text = "Cambridge", Value = "Ca"
                    },
                   new SelectListItem {
                        Text = "Oxford", Value = "Ox"
                    },
                    new SelectListItem {
                        Text = "Sheffield", Value = "Sh"
                    }                
             },
         "--Select Cities--",
    new {
        @class = "form-control",
        required = true,
        multiple = "multiple"
    }
        )
    </div>
</div>

Here is my controller:

[HttpPost]
    public ActionResult Insert( FormCollection frm ) {
        Models.ProjectInfo p = new Models.ProjectInfo();
        String[] Cities= frm.GetValues( "City" );
        p.ContractId = frm[ "ContractId" ];
        p.Year = Convert.ToDecimal( frm[ "Year" ] );
        p.City = Cities.ToString();
        p.Location = frm[ "Location" ];
        // Insert into the Database
            AddProjectInfo( p );
            ViewBag.ResponseMessage = "Submitted !";

    }

I know how to do that using JavaScript but dont know how C# can handle that. Thanks you!

 @Html.ListBoxFor(m => m.location_code, Model.location_type)        
    [HttpPost]
        public string SaveResults(List<int> location_code)
        {

            if (location_code!= null)
            {
                return string.Join(",", location_code);
            }
            else
            {
                return "No values are selected";
            }
        }

I will tell you upfront that I wrote these examples without testing it, but it's just to give you a general idea of how to proceed correctly with dropdown lists / list boxes. Also, in the end, I will leave the link to my GitHub where I have a simple project which I wrote some time ago specially for cases like this.

So, let's get started. For the sake of simplicity I would rather have the dropdown list being created in the Controller. For example:

Let's assume you have a Model:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string City { get; set; }

    [NotMapped]
    public SelectList CitySelectList { get; set; }
}

Notice the CitySelectList , which is NotMapped since we don't want it to be connected to the DB. The value of CitySelectList will be saved in the DB through City

And then you have an Action Method:

public ActionResult Insert()
{
    var person = new Person { CitySelectList = new SelectList(
    new List<SelectListItem>
        {
            new SelectListItem { Text = "Cambridge", Value = "Ca" },
            new SelectListItem { Text = "Oxford", Value = "Ox" },
            new SelectListItem { Text = "Sheffield", Value = "Sh" }
        }, "Value", "Text") };

    return View(person);
}

Here you can see that I am creating an instance of Person and passing it to the View. This is the best way to load a View with predefined values. And the most important predefined value in this case is the dropdown list.

The View would look more or less like this:

@model Person

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-group">
        @Html.LabelFor(m => m.Name, htmlAttributes: new { @class = "control-label" })
        @Html.EditorFor(m => m.Name, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Surname, htmlAttributes: new { @class = "control-label" })
        @Html.EditorFor(m => m.Surname, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(m => m.Surname, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.City, htmlAttributes: new { @class = "control-label" })
@* Important *@
        @Html.EditorFor(m => m.CitySelectList, new { htmlAttributes = new { @class = "form-control", multiple = "multiple" } })
@* /Important *@
        @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
    </div>

}

As you can see I am calling the dropdown list through an EditorFor passing 2 htmlAttributes. The most important is multiple = "multiple" since this is the one which will define the type of item list I am going to show in the page. How? Through an Editor Template built specially to handle it. If you are not familiar with its concept and usage you can check this website for start. The editor template can be seen below:

@model SelectList

@{
    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
}

@if (!htmlAttributes.ContainsKey("multiple"))
{
    @Html.DropDownListFor(m => m.SelectedValue, Model.SelectListItems, htmlAttributes)
}
else
{
    @Html.ListBoxFor(m => m.SelectedValues, Model.SelectListItems, htmlAttributes)
}

One detail on this particular Editor Template: Have you noticed that I am creating the Dropdown List / List Box for the SelectedValue(s)? That is something which might cause a bit of headache when you get all the values but you can handle, in your POST method, in this way:

[HttpPost]
public ActionResult Insert(Person person)
{
    person.City = person.CitySelectList.SelectedValues;
    // Some code goes here
    return View();
}

That should be it. But, as I said before, I have a working code here so you can run and see how it works. And also some explanation of that code from GitHub right here in case you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM