简体   繁体   English

如何在C#中存储多个选择/下拉列表

[英]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. 我是MVC和C#的新用户,我想通过一个项目尝试让用户从列表中选择城市,然后将其存储到数据库中。 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. 我知道如何使用JavaScript做到这一点,但不知道C#如何处理它。 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. 另外,最后,我将保留到我的GitHub的链接,那里有一个简单的项目,该项目是我前一段时间专门为此类情况编写的。

So, let's get started. 因此,让我们开始吧。 For the sake of simplicity I would rather have the dropdown list being created in the Controller. 为了简单起见,我宁愿在Controller中创建下拉列表。 For example: 例如:

Let's assume you have a Model: 假设您有一个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. 注意CitySelectList ,它是NotMapped因为我们不希望将其连接到数据库。 The value of CitySelectList will be saved in the DB through City CitySelectList的值将通过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. 在这里,您可以看到我正在创建Person的实例并将其传递给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. 如您所见,我正在通过EditorFor调用下拉列表,以传递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. 最重要的是multiple = "multiple"因为这将定义我将在页面中显示的项目列表的类型。 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)? 关于此特定编辑器模板的一个细节:您是否注意到我正在为SelectedValue创建下拉列表/列表框? 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: 当您获得所有值时,可能会有些头疼,但是您可以通过POST方法以这种方式进行处理:

[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. 而且还从GitHub代码的一些解释在这里如果你需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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