gpt4 book ai didi

c# - ASP.NET MVC 模型与 ListBoxFor 和 DropDownListFor 助手的绑定(bind)

转载 作者:可可西里 更新时间:2023-11-01 08:40:41 24 4
gpt4 key购买 nike

我有以下模型:

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

我使用以下代码将文本框绑定(bind)到服务器名,效果很好:

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

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

更新:我不认为我在这里提供了足够的信息

在 Controller 中,ViewData["osTypes"] 被设置为一个列表,其中包含一些从 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;
}
});

我觉得我在这里做错了一些可怕的事情,任何事情都是有帮助的。

最佳答案

首先,为了使模型绑定(bind)器正常工作,您的所有属性都需要有 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;"})

关于c# - ASP.NET MVC 模型与 ListBoxFor 和 DropDownListFor 助手的绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19143126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com