gpt4 book ai didi

asp.net-mvc - MVC ListBoxFor 引发 "value cannot be null"异常

转载 作者:行者123 更新时间:2023-12-02 08:59:36 24 4
gpt4 key购买 nike

我正在尝试使用 Html.ListBoxFor 帮助程序来显示列表框并返回选定的 Id。 dataValueField 不是字符串有问题吗?

如果模型中包含的 SelectList 使用整数作为 dataValueField,则在 View 中呈现列表时会出现“值不能为空 - 参数名称:源”异常。

如果 ID 更改为字符串,则一切正常,所选 ID 会传回 View 。

有什么想法吗?

这是 Controller (基于缩减的新项目)

namespace Mvc2.Controllers
{
public class ViewModel
{
public int TestId { get; set; } // if this is a string it works ok
public SelectList ListData {get; set;}
}

[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new ViewModel();
model.TestId = 1; // code corrected after Lazarus' comment

var lst = new[] { new { Id = 1, Name = "cat" }, new { Id = 2, Name = "dog" } };
model.ListData = new SelectList(lst, "Id", "Name");

return View("TestView", model);
}

public ActionResult TestSubmit(ViewModel returnedModel)
{
int i = 99; // break here - returnedModel has correct TestId when declared as string
}
}
}

这是 View - 在 ListBoxFor 行上崩溃

<%using (Html.BeginForm("TestSubmit", "Home")) { %>

<%=Model.TestId %><br />
<%=Html.ListBoxFor(m => m.TestId, Model.ListData) %>

<br />
<input type="submit" value="Save" />

<%} %>

最佳答案

您为所选值传递的表达式需要是 IEnumerable,因为 ListBoxFor 支持多个所选项目。

关于asp.net-mvc - MVC ListBoxFor 引发 "value cannot be null"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2288729/

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