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

我有以下型号:

[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)ViewData["osTypes"]),"Value","Text"), new { @class = "fixed" }) @Html.ListBoxFor(m => m.applications, new MultiSelectList((List)ViewData["appList"]), new {style="display:none;"}) 

对我在这里做错了什么的想法?

更新:我认为我没有提供足够的信息

在控制器中,ViewData [“osTypes”]设置为List,其中包含从WebAPI中提取的一些默认值:

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

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

 ViewData["appList"] = new List(); 

对于应用程序列表,用户填写文本框并点击按钮将数据添加到应用程序列表框:

在此处输入图像描述

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('' + svc + ''); $(ul).append('
  • ') txt.val(""); return false; } });
  • 我有一种感觉,我在这里做了一些可怕的错误,任何事都有帮助。

    首先,为了使模型绑定器工作,所有属性都需要有getter和setter。

    所以改变:

     public string[] applications; 

    至:

     public string[] applications { get; set; } 

    并且为了让ListBox正确显示数据使用

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