簡體   English   中英

使用ListBoxFor和DropDownListFor Helpers的ASP.NET MVC模型綁定

[英]ASP.NET MVC Model Binding With ListBoxFor & DropDownListFor Helpers

我有以下型號:

[Required (ErrorMessage="Server Name Required")]
[StringLength(15, ErrorMessage = "Server Name Cannot Exceed 15 Characters")]
public string servername { get; set; }
[Required(ErrorMessage = "Server OS Type Required")]
public string os { get; set; }
public string[] applications;

我使用以下代碼將文本框綁定到服務器名稱,工作正常:

@Html.TextBoxFor(m => Model.servername, new {@class="fixed", @id="serverName"})

我正在使用操作系統的下拉列表和應用程序的列表框,這兩個列表框都沒有在提交時正確填充模型。

 @Html.DropDownListFor(m => m.os , new SelectList( ((List<SelectListItem>)ViewData["osTypes"]),"Value","Text"), new { @class = "fixed" })

 @Html.ListBoxFor(m => m.applications, new MultiSelectList((List<SelectListItem>)ViewData["appList"]), new {style="display:none;"})

對我在這里做錯了什么的想法?

更新:我認為我沒有提供足夠的信息

在控制器中,ViewData [“osTypes”]設置為List,其中包含從WebAPI中提取的一些默認值:

List<string> osTypes = FastFWD_SITE.Helpers.GetJsonObj._download_serialized_json_data<List<string>>(getOsTypeUrl);
List<SelectListItem> osTypeList = new List<SelectListItem>();
foreach (string osType in osTypes)
{
    osTypeList.Add(new SelectListItem { Text = osType });
}
ViewData["osTypes"] = osTypeList;

ViewData [“appList”]被發送到空列表,如下所示:

ViewData["appList"] = new List<SelectListItem>();

對於應用程序列表,用戶填寫文本框並點擊按鈕將數據添加到應用程序列表框:

在此輸入圖像描述

Jquery將項添加到列表框:

$("#addItem").click(function () {
        var txt = $("#appName");
        var svc = $(txt).val();  //Its Let you know the textbox's value   
        var lst = $("#serverSpecification_applications");
        var ul = $("#itemList");
        var options = $("#serverSpecification_applications option");
        var iList = $("#itemList li");
        var alreadyExist = false;
        $(options).each(function () {
            if ($(this).val() == svc) {
                alreadyExist = true;
                txt.val("");
                return alreadyExist;
            }
        });
        if (!alreadyExist) {
            $(lst).append('<option value="' + svc + '" selected=true>' + svc + '</option>');
            $(ul).append('<li id="' + svc + '"><label>' + svc + '<input type="checkbox" id="' + svc + '" onclick="removeItem(this.id)"/></label>')
            txt.val("");
            return false;
        }           
    });

我有一種感覺,我在這里做了一些可怕的錯誤,任何事都有幫助。

首先,為了使模型綁定器工作,所有屬性都需要有getter和setter。

所以改變:

public string[] applications;

至:

public string[] applications { get; set; }

並且為了讓ListBox正確顯示數據使用

@Html.ListBoxFor(m => m.applications, 
    new MultiSelectList((List<SelectListItem>)ViewData["appList"], "Value", "Text"), 
    new {style="display:block;"})

暫無
暫無

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

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