gpt4 book ai didi

c# - MVC - 从 ListBoxFor 获取 ViewModel 对象

转载 作者:行者123 更新时间:2023-11-30 20:10:43 25 4
gpt4 key购买 nike

我在提交表单后尝试获取自己的 View 模型,但出现以下错误:“无法将类型为‘System.String[]’的对象转换为类型‘System.String’”

这是我的代码:

View 模式:

public class SoftwarePackages
{
public string[] PermissionsList { get; set; }
}

aspx

<%: Html.ListBoxFor(model => model.PermissionsList, new List<SelectListItem>(), new { size = 10 })%>

控制者

[HttpPost]
public ActionResult Index(SoftwarePackages softwarePackages)
{
code...code...code
}

问题是什么?

谢谢

祖多尔

最佳答案

以下对我来说效果很好:

型号:

public class SoftwarePackages
{
public string[] PermissionsList { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}

Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
var model = new SoftwarePackages
{
Items = new SelectList(new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}, "Value", "Text")
};
return View(model);
}

[HttpPost]
public ActionResult Index(SoftwarePackages softwarePackages)
{
// do something with softwarePackages.PermissionsList
...
}
}

查看:

<% using (Html.BeginForm()) { %>
<%: Html.ListBoxFor(model => model.PermissionsList, Model.Items, new { size = 10 })%>
<input type="submit" value="OK" />
<% } %>

关于c# - MVC - 从 ListBoxFor 获取 ViewModel 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4641349/

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