使用ListBoxFor和&amp ;;的ASP.NET MVC模型绑定DropDownListFor助手

时间:2013-10-02 17:31:26

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我有以下型号:

[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>();

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

enter image description here

将项目添加到列表框的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;
        }           
    });

我有一种感觉,我在这里做了一些可怕的错误,任何事都有帮助。

1 个答案:

答案 0 :(得分:17)

首先,为了使模型绑定器工作,所有属性都需要具有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;"})
相关问题