zoukankan      html  css  js  c++  java
  • MVC ListBoxFor raises “value cannot be null” exception

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

    <%} %>
  • 相关阅读:
    bzoj4864 [BeiJing 2017 Wc]神秘物质
    HNOI2011 括号修复
    bzoj2402 陶陶的难题II
    ZJOI2008 树的统计
    USACO09JAN 安全出行Safe Travel
    HAOI2015 树上操作
    hdu5126 stars
    BOI2007 Mokia 摩基亚
    SDOI2011 拦截导弹
    国家集训队 排队
  • 原文地址:https://www.cnblogs.com/glj1203/p/1934973.html
Copyright © 2011-2022 走看看