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

    <%} %>
  • 相关阅读:
    PostgreSQL初识,编译安装
    关于iframe的父页面调取子页面里的事件(父往子里传)
    织梦常用代码
    获取月份的最后一天是几号
    获取今天、昨天、一周前的日期
    时分秒倒计时的js实现
    CSS初始化代码
    正则表达式
    utils.js文件;一些常用方法的备份
    js replace替换一段文本中所有的相同字符
  • 原文地址:https://www.cnblogs.com/glj1203/p/1934973.html
Copyright © 2011-2022 走看看