簡體   English   中英

如何在C#中存儲多個選擇/下拉列表

[英]how to store Multiple selction / Dropdownlist in C#

我是MVC和C#的新用戶,我想通過一個項目嘗試讓用戶從列表中選擇城市,然后將其存儲到數據庫中。 我已經閱讀了幾篇關於此的文章,但無法弄清楚如何解決我的問題。 我可以存儲表格中的所有其他項目:

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

但對於城市,它僅存儲第一個選定項目,而不是全部。 你能幫我解決這個問題嗎?

這是我的看法:

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

這是我的控制器:

[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 !";

    }

我知道如何使用JavaScript做到這一點,但不知道C#如何處理它。 謝謝!

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

我將事先告訴您,我在編寫這些示例時沒有進行測試,但這只是為了讓您大致了解如何正確使用下拉列表/列表框。 另外,最后,我將保留到我的GitHub的鏈接,那里有一個簡單的項目,該項目是我前一段時間專門為此類情況編寫的。

因此,讓我們開始吧。 為了簡單起見,我寧願在Controller中創建下拉列表。 例如:

假設您有一個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; }
}

注意CitySelectList ,它是NotMapped因為我們不希望將其連接到數據庫。 CitySelectList的值將通過City保存在數據庫中

然后您有一個操作方法:

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

在這里,您可以看到我正在創建Person的實例並將其傳遞給View。 這是用預定義值加載視圖的最佳方法。 在這種情況下,最重要的預定義值是下拉列表。

視圖將大致如下所示:

@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>

}

如您所見,我正在通過EditorFor調用下拉列表,以傳遞2個htmlAttributes。 最重要的是multiple = "multiple"因為這將定義我將在頁面中顯示的項目列表的類型。 怎么樣? 通過專門為處理它而設計的編輯器模板。 如果您不熟悉它的概念和用法,可以查看此網站以開始使用。 編輯器模板如下所示:

@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)
}

關於此特定編輯器模板的一個細節:您是否注意到我正在為SelectedValue創建下拉列表/列表框? 當您獲得所有值時,可能會有些頭疼,但是您可以通過POST方法以這種方式進行處理:

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

應該是這樣。 但是,正如我之前所說,我在這里有一個有效的代碼因此您可以運行並查看其工作方式。 而且還從GitHub代碼的一些解釋在這里如果你需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM