I am trying to use the Html.ListBoxFor helper to show a list box and return the selected Id. Is there a problem with the dataValueField not being a string?

If the SelectList contained in the model uses integers as the dataValueField then I get a "Value cannot be null - Parameter name: Source" exception raised when the list is rendered in the view.

If the Id is changed to a string then everything works and the selected Id is passed back to the view.

Any ideas?

Here is the controller (based on a cut down new project)

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
        }
    }
}

here is the View - crashes on the ListBoxFor line

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

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

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

<%} %>
推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"