System.MissingMethodException: No parameterless co

2019-03-01 20:15发布

问题:

I'm using MVC 2.0 with a Html.ListBoxFor as below:

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

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

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

    <% } %>

When I click the input submit button below with nothing selected, it posts back fine, when I select one of the 3 items in the listbox it throws this error:

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

Any ideas? here is my controller code:

 [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);
    }
}

回答1:

Does your LogOnModel have a parameterless constructor? It needs one for the DefaultModelBinder to instantiate it. Additionally, when you post the exception, please post the full stack trace from the exception object, else we're simply guessing where the error actually took place.



回答2:

This error is coming from the ControllerFactory not the View. It is stating that you don't have a paramerless constructor in your Controller. The DefaultControllerFactory for ASP.NET MVC can only instantiate a Controller with a public parameter less constructor. If you plugin your own ControllerFactory and use some DI/IoC tool you can bypass this limitation.