MVC ViewModel Error - No parameterless constructor defined for this object

后端 未结 3 952
一个人的身影
一个人的身影 2020-12-09 12:52

I would like to know how can I use my ViewModel on the Create Action? I tried several examples I found here in the forum, but none solved my problem. I\'ve been racking my b

相关标签:
3条回答
  • 2020-12-09 13:02

    For me the problem was in the BeginForm() method itself. It looked like this:

    @using (Html.BeginForm("MyAccount", "MyController", Model))
    

    Copied and pasted in from another project's Login page, which doesn't have a dropdown.

    Anyway, remove the Model from the parameter list and it all works just fine :)

    0 讨论(0)
  • 2020-12-09 13:08

    If I had a nickel for every time I've seen this problem. It's typically related to the naming of your model properties and how you use them in a DropDownList. 99.999% of the time it's because people are using Html.DropDownList() and naming it the same as their SelectList. This is one reason you should use the strongly typed DropDownListFor.

    In this case, your problem is that you have SelectLists named Genres and Artists, then in your view you have:

    @Html.DropDownList("Genres", String.Empty)
    @Html.DropDownList("Artists", String.Empty)
    

    See, same name.

    What you should do is change your Model to make the SelectLists be named GenreList and ArtistList. Then, change your view to use strongly typed model.

    @Html.DropDownListFor(m => m.AlbumItem.GenreID, Model.GenreList)
    @Html.DropDownListFor(m => m.AlbumItem.ArtistID, Model.ArtistList)
    

    The reason this happens is that you are posting a value called Genres to the controller. The default model binder dutifully looks in the model to find something called Genres and instantiate it. But, rather than an ID or string, it finds a SelectList named Genres, and when it tries to instantiate it, it finds there is no default constructor.

    Thus your error. SO is filled with questions asking about this same thing.

    0 讨论(0)
  • 2020-12-09 13:18

    Similar to Erik Funkenbusch's answer I'd added a DropDownList to my form, however in my case it wasn't (and wasn't intended to be) submitted with the form as it was outside of the <form></form> tags:

    @Html.DropDownList("myField", Model.MyField)
    

    As the Model contained the field for display only, this also caused the No parameterless constructor defined for this object error because the field wasn't submitted at all.

    In this case I fixed it by adding an exclude binding:

    public ActionResult Foo(int id, int? page, [Bind(Exclude = "MyField")]MyModel model)
    
    0 讨论(0)
提交回复
热议问题