MVC ListBoxFor raises "value cannot be null" exception

Source: Internet
Author: User

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" />

<%} %>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.