Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Custom ViewModel and auto binding

I have a custom ViewModel defined as :

public class SampleFormViewModel
{
    public SampleFormViewModel(SelectList companies, Widget widget)
    {
        Companies = companies;
        Widget = widget;
    }

    public SelectList Companies { get; private set; }
    public Widget Widget { get; private set; }
}

In my Edit POST handler I have the following entry:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(SampleFormViewModel model)
{

Edit form is set up as:

Inherits="System.Web.Mvc.ViewPage<Sample.Web.Models.SampleFormViewModel>"

And it just blows up, not sure what’s going on, has the following error: No parameterless constructor defined for this object. Certain I’m missing something really obvious here. Some background, the GET works perfectly and display the dropdown from the SelectList as expected. I’m guessing the auto-binding back to the custom view model is what is failing but not sure what to do about it.

like image 298
Craig McGuff Avatar asked Apr 19 '09 13:04

Craig McGuff


1 Answers

You need to have a parameterless constructor and I believe that the properties need to have public setters. The default binder creates the object using a constructor that takes no parameters, then uses reflection on the public properties to set values from the form/query parameters.

public class SampleFormViewModel
{
    public SampleFormViewModel() { }

    public SelectList Companies { get; set; }
    public Widget Widget { get; set; }
}

I suspect, though, that what you really want to do is not get the view model, but the underlying Widget model and select list value on form post. I don't think the binder will be able to reconstruct a SelectList on post since it only has the selected value in the parameters.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit( int CompanyID, Widget widget )
{
}
like image 96
tvanfosson Avatar answered Sep 19 '22 12:09

tvanfosson