System.MissingMethodException:没有为此对象定义的无参数构造函数

时间:2010-08-13 13:58:22

标签: asp.net-mvc asp.net-mvc-2 binding model listbox

我正在使用带有Html.ListBoxFor的MVC 2.0,如下所示:

<% using (Html.BeginForm()) { %>

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

        <%= Html.ListBoxFor(x => x.lstTest, new MultiSelectList(new [] {"someone", "crap", "why"})) %>

    <% } %>

当我单击下面的输入提交按钮时没有选择任何内容时,它会回复正常,当我选择列表框中的3个项目之一时会抛出此错误:

 System.MissingMethodException: No parameterless constructor defined for this object.

有什么想法吗?这是我的控制器代码:

 [HandleError]
public class HomeController : Controller
{
    public HomeController()
    {

    }

    public ActionResult Index()
    {
        ViewData["Message"] = "Test Harness";

        return View();
    }

    [HttpGet]
    public ActionResult About()
    {
        ViewData["mykey"] = "Test Harness";

        LogOnModel model = new LogOnModel();
        model.lstTest = new MultiSelectList(new [] {"A", "B", "C"});

        return View(model);
    }


    [HttpPost]
    public ActionResult About(LogOnModel model)
    {
        ViewData["mykey"] = "Test Harness";

        model.lstTest = new MultiSelectList(new [] { "" });

        return View(model);
    }
}

2 个答案:

答案 0 :(得分:4)

您的LogOnModel是否具有无参数构造函数?它需要一个DefaultModelBinder来实例化它。此外,当您发布异常时,请从异常对象发布完整堆栈跟踪,否则我们只是猜测实际发生错误的位置。

答案 1 :(得分:0)

此错误来自ControllerFactory而非View。它表明你的Controller中没有无命名的构造函数。 ASP.NET MVC的DefaultControllerFactory只能使用公共参数less constructor实例化Controller。如果你插入自己的ControllerFactory并使用一些DI / IoC工具,你可以绕过这个限制。