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

    <%} %>
  • 相关阅读:
    COM组件开发实践(七)---多线程ActiveX控件和自动调整ActiveX控件大小(上)
    A Complete ActiveX Web Control Tutorial
    C++使用VARIANT实现二维数组的操作
    用户自定义结构数据与VARIANT转换
    VS2008中使用JSONCPP方法小结
    HDOJ 2030 汉字统计
    HDOJ 1312 (POJ 1979) Red and Black
    POJ 1503 Integer Inquiry 简单大数相加
    POJ 1936 All in All
    枚举法
  • 原文地址:https://www.cnblogs.com/glj1203/p/1934973.html
Copyright © 2011-2022 走看看