MVC ListBoxFor raises “value cannot be null” exception

岁酱吖の 提交于 2019-12-06 14:21:43

The expression you are passing for the selected values needs to be IEnumerable because ListBoxFor supports multiple selected items.

Answering my own question;

I am unconviced by the comments that this might be a bug which is waiting to be fixed because I get it in RC2 and in MVC 1 (I copied the code back to a project in that release). Anyway I have implemented a work around for now which is to:-

(a) Add a dummy string version of the Id to the model (TestId)

public class ViewModel
{
    public string TestId { get; set; } // dummy Id as a string
    public List<DataToShow> Data { get; set; }
    public SelectList ListData {get; set;}
}

(b) Display the list but retrieve the value as the dummy TestId - note that the list still dumps the data values as integers!

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

(c) Copy the dummy string value into its proper integer location in the action

public ActionResult TestSubmit(ViewModel returnedModel)
{
    MyModel.DataId = Int32.Parse(returnedModel.TestId);

Hope this is of some Help.

George Stocker

This is a known issue with ASP.NET MVC 2. It should be fixed in the March release.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!