Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 9802
  • Last Modified:

MVC 5 "no parameterless constructor defined for this object" error

Hi

I have an MVC 5 site which contains two dropdown boxes and a Radiobutton group. However, when I click the "Submit" button on my site I get an "no parameterless constructor defined for this object" error.

This is my Controller:
public class VisitListController : Controller
  {
    // GET: VisitList
    public ActionResult ViewVisitList()
    {
      //Opretter variable til at indeholde dropdownlister og radio button group
      List<RecyclePoints> PointDDL = new List<RecyclePoints>();
      List<LicensePlates> PlateDDL = new List<LicensePlates>();
      List<ProductTypes> ProductsRBG = new List<ProductTypes>();

      //Gets RecyclePoint list
      PointDDL = GetRecyclePoints(); 
      SelectList ObjRecyclePointsToBind = new SelectList(PointDDL, "PointId", "PointName", 0);
      
      //Gets License plate list
      PlateDDL = GetLicensePlates();
      SelectList ObjLicensePLatesToBind = new SelectList(PlateDDL, "CardId", "LicensePlate", 0);

      //Gets products
      ProductsRBG = GetProductTypes();
      SelectList ObjProductsToBind = new SelectList(ProductsRBG, "ProductTypeId", "ProductName", 0);

      //Opretter ny ModelData
      ModelData mData = new ModelData();

      //Tilføjer der hentede dropdownliste og radio button group til mData
      mData.Points = ObjRecyclePointsToBind;
      mData.Plates = ObjLicensePLatesToBind;
      mData.Products = ObjProductsToBind;

      return View(mData);
    }
.
.
.
.

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult UpdateVisitList(ModelData Model)
    {
      //Handles page submit
    }
}

Open in new window


My Model looks like this:

namespace GbizzVirk_dk.Models
{
  public class ModelData
  {
    [Display(Name="Vælg genbrugsplads:")]
    public SelectList Points { get; set; }

    [Display(Name="Vælg nummerplade:")]
    public SelectList Plates { get; set; }

    [Display(Name="Vælg produkttype:")]
    public SelectList Products {get; set;}
  }

  //Radiobutton group til valg af produkttype
  public class ProductTypes
  {
    public int ProductTypeId { get; set; }
    public string ProductName { get; set; }
  }

  //DropDownList til RecyclePoint Dropdown
  public class RecyclePoints
  {
    public int PointId { get; set; }
    public string PointName { get; set; }
  }

  //Dropdown til Licenseplates
  public class LicensePlates
  {
    public int CardId { get; set; }
    public string LicensePlate { get; set; }
  }
}

Open in new window


And my view looks like this:
@model GbizzVirk_dk.Models.ModelData

@{
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Sorter besøgsliste</h3>

@using (Html.BeginForm("UpdateVisitList", "VisitList")) 
{ 
  @Html.AntiForgeryToken()
  @Html.ValidationSummary()
  
  <fieldset>
    <legend>Besøgsoversigt</legend>
    <div class="row">
      <div class="col-sm-4">
        <div class="form-group">
          <div class="input-append date" id="dpFromDate" data-date="13-02-2012" data-date-format="dd-mm-yyyy">
            <input type="date" id="FromDate" value="13-02-2012" class="form-control" />
            <div class="description">Datoen skal være i formatet dd-MM-åååå</div>
          </div>
        </div>
      </div>
      <div class="col-sm-4">
        <div class="input-append date" id="dp3" data-date="14-02-2012" data-date-format="dd-mm-yyyy">
          <div class="form-group">
           @* @Html.LabelFor(m => m.ToDate)*@
            <input type="date" id="startdato" value="14-02-2012" class="form-control" />
            <div class="description">Datoen skal indtastes i formatet dd-mm-åååå</div>
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-4">
        <div class="form-group">
          @Html.LabelFor(m => m.Points)
          @Html.DropDownList("RecyclePoint", new SelectList(Model.Points, "Value", "Text", Model.Points.SelectedValue), new { @class = "form-control" })
        </div>
      </div>
      <div class="col-sm-4">
        <div class="form-group">
          @Html.LabelFor(m => m.Plates)
          @Html.DropDownList("LicensePlates", new SelectList(Model.Plates, "Value", "Text", Model.Plates.SelectedValue), new { @class = "form-control" })
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-sm-4">
        <div class="form-group">
          @{
            foreach (var Product in Model.Products)
            {
              @Html.RadioButtonFor(m => m.Products, new { id = Product.Value, @class="radio" })
              @Html.Label(Product.Text)
            }
          }
        </div>
      </div>
    </div>

    <div class="row">
      <div class="col-sm-4">
        <div class="form-group">
          <input type="submit" value="Hent data" class="btn-primary" />
        </div>
      </div>
    </div>
  </fieldset>

Open in new window


From searching the net, I gather that I need to create a parameterless default constructor for MVC to call, but I struggle to get this done correctly. Can anyone give me any hints or tips as to where and how to make this??
0
poultarp
Asked:
poultarp
  • 5
  • 4
1 Solution
 
Carl TawnSystems and Integration DeveloperCommented:
If the error is referring to the ModelData class, then you could try adding an explicit parameterless constructor:
  public class ModelData
  {
    public ModelData() 
    { }

    [Display(Name="Vælg genbrugsplads:")]
    public SelectList Points { get; set; }

    [Display(Name="Vælg nummerplade:")]
    public SelectList Plates { get; set; }

    [Display(Name="Vælg produkttype:")]
    public SelectList Products {get; set;}
  }

Open in new window

0
 
poultarpAuthor Commented:
Hi Carl

Thank you for your suggestion. Unfortunatly it did not work. I still get the same error when I click the "Submit" button.
0
 
Carl TawnSystems and Integration DeveloperCommented:
I wasn't really expecting it to work to be honest :)

Without any context it is difficult to know specifically which object it is complaining about. Does the stack trace give you any information about which class is being instantiated?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
poultarpAuthor Commented:
Hi

I'm not an export when it comes to reading stacktraces, but this is the stracktrace the error returns:

[MissingMethodException: Der er ikke defineret en konstruktør uden parametre for dette objekt.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +197

[MissingMethodException: Der er ikke defineret en konstruktør uden parametre for dette objekt. Object type 'System.Web.Mvc.SelectList'.]
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +233
   System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +284
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +281
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +17
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +382
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +101
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +55
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1197
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +330
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +338
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +743
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Open in new window


if that is any help.
0
 
Kelvin McDanielSr. Developer/ConsultantCommented:
There's something else going on here...

... under the C# covers you get a parameterless constructor on non-static class unless you provide your own. Also, looking at your GET in the controller... if the problem was a missing constructor that method would be blowing up as well.

Is your view code a 100% copy and paste? If so, it looks like you're missing the closing curly brace on the Form (looks like it should be line #72 in your code). If that curly brace is not there try adding that and see what happens.
0
 
Carl TawnSystems and Integration DeveloperCommented:
It's the use of SelectList in your model that is causing the issue. SelectList doesn't have a default constructor, so cannot be instantiated by MVC.

You are using SelectList in your View, which is correct, but you should be using something like List<> in your model to pass the data needed to the view, rather than having a SelectList in the model itself.
0
 
poultarpAuthor Commented:
@Carl Tawn

If I change my Model from:

public class ModelData
  {
    [Display(Name="Vælg genbrugsplads:")]
    public SelectList Points { get; set; }

    [Display(Name="Vælg nummerplade:")]
    public SelectList Plates { get; set; }

    [Display(Name="Vælg produkttype:")]
    public SelectList Products {get; set;}

    public List<VisitList> VisitList { get; set; }

    [Display(Name="Vælg fra dato:")]
    public string FromDate { get; set; }

    [Display(Name = "Vælg til dato:")]
    public string ToDate { get; set; }
  }

Open in new window


To this:
public class ModelData
  {
    [Display(Name="Vælg genbrugsplads:")]
    public List<SelectList> Points { get; set; }

    [Display(Name="Vælg nummerplade:")]
    public List<SelectList> Plates { get; set; }

    [Display(Name="Vælg produkttype:")]
    public List<SelectList> Products {get; set;}

    public List<VisitList> VisitList { get; set; }

    [Display(Name="Vælg fra dato:")]
    public string FromDate { get; set; }

    [Display(Name = "Vælg til dato:")]
    public string ToDate { get; set; }
  }

Open in new window


Then I am having problems with the code in my Controller. I first create a

List<RecyclePoints> PointDDL = new List<RecyclePoints>();

to hold my data for one of the dropdownlists. I fill this using a function which returns a

List<RecyclePoints>

But when I try to bind this to the "Points" list in my Model, I get an error saying that:

"Cannot implicitly convert type 'System.Collections.Generic.List<GbizzVirk_dk.Models.RecyclePoints>' to 'System.Collections.Generic.List<System.Web.Mvc.SelectList>"

Any ideas what I am missing or doing wrong?
0
 
Carl TawnSystems and Integration DeveloperCommented:
I would expect your model to look more like:
public class ModelData
 {
    [Display(Name="Vælg genbrugsplads:")]
    public List<RecyclePoints> Points { get; set; }

    [Display(Name="Vælg nummerplade:")]
    public List<LicensePlates> Plates { get; set; }

    [Display(Name="Vælg produkttype:")]
    public List<ProductTypes> Products {get; set;}

    public List<VisitList> VisitList { get; set; }

    [Display(Name="Vælg fra dato:")]
    public string FromDate { get; set; }

    [Display(Name = "Vælg til dato:")]
    public string ToDate { get; set; }
  }

Open in new window

And your controller action to be more like:
public ActionResult ViewVisitList()
    {
      //Opretter ny ModelData
      ModelData mData = new ModelData();

      //Tilføjer der hentede dropdownliste og radio button group til mData
      mData.Points = GetRecyclePoints();
      mData.Plates = GetLicensePlates();
      mData.Products = GetProductTypes();

      return View(mData);
    }

Open in new window

The you use SelectList in your view to bind to the items in the List<>s in your model.
0
 
poultarpAuthor Commented:
@Carl

Thank you for your help so far!

I'm an now struggling with binding the data to the DropDownList.

To reap on what I am doing so far:

My Model looks like this:
public class ModelData
  {
    [Display(Name = "Vælg genbrugsplads:")]
    public List<RecyclePoints> Points { get; set; }

    [Display(Name = "Vælg nummerplade:")]
    public List<LicensePlates> Plates { get; set; }

    [Display(Name = "Vælg produkttype:")]
    public List<ProductTypes> Products { get; set; }

    public List<VisitList> VisitList { get; set; }

    [Display(Name = "Vælg fra dato:")]
    public string FromDate { get; set; }

    [Display(Name = "Vælg til dato:")]
    public string ToDate { get; set; }
  }

  //Radiobutton group til valg af produkttype
  public class ProductTypes
  {
    public int ProductTypeId { get; set; }
    public string ProductName { get; set; }
  }

  //DropDownList til RecyclePoint Dropdown
  public class RecyclePoints
  {
    public int PointId { get; set; }
    public string PointName { get; set; }
  }

  //Dropdown til Licenseplates
  public class LicensePlates
  {
    public int CardId { get; set; }
    public string LicensePlate { get; set; }
  }

  //Liste til besøgsoversigt
  public class VisitList
  {
    public string RegistrationId { get; set; }
    public string CardId { get; set; }
    public string RegistrationDate { get; set; }
    public string LicensePlate { get; set; }
    public string VisitType { get; set; }
    public string Amount { get; set; }
    public string Price { get; set; }
    public string RecyclePoint { get; set; }
    public List<VisitList> VList { get; set; }
    
  }

Open in new window


In my Controller I have this function which gets the data for the dropdownlist from SQL:
public List<RecyclePoints> GetRecyclePoints()
    {
      List<RecyclePoints> objRecPoints = new List<RecyclePoints>();

      //Henter data til Genbrugsplads dropdownliste
      using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gbizz"].ConnectionString))
      {
        con.Open();
        SqlCommand sqlCom;
        SqlDataReader sqlReader;

        sqlCom = new SqlCommand("RecyclePointGetInformation", con);
        sqlCom.CommandType = CommandType.StoredProcedure;
        sqlCom.Parameters.Add("@MunicipalityNo", SqlDbType.Int).Value = 630;
        sqlCom.Parameters.Add("@IsVirkDK", SqlDbType.Int).Value = 1;
        sqlCom.Parameters.Add("@GetType", SqlDbType.Int).Value = 1;

        sqlReader = sqlCom.ExecuteReader();

        if (sqlReader.HasRows)
        {
          while (sqlReader.Read())
          {
            RecyclePoints pDDL = new RecyclePoints();
            pDDL.PointId = Convert.ToInt32(sqlReader["PointId"].ToString());
            pDDL.PointName = sqlReader["PointName"].ToString();
            objRecPoints.Add(pDDL);
          }
        }
        sqlReader.Close();
        sqlReader.Dispose();
        sqlCom.Dispose();
        con.Close();
        con.Dispose();
      }
      return objRecPoints;
    }

Open in new window


In the Public ActionResult I create a new instance of the "ModelData" like this:

ModelData mData = new ModelData();

and add the list of Recyclingpoints to the Points list like this:

mData.Points = GetRecyclePoints();

and I return mData to the View like this:

return View(mData);

Now, in my View, I have tried pretty much every way I can think of using @Html.DropDownList and @Html.DropDownListFor in order to bind the data to the dropdownlist, but I just can't get it right.

Any ideas how to get over this last hurdle??
0
 
poultarpAuthor Commented:
I GOT IT! :-)

I was able to populte the dropdownlist like this:

@Html.DropDownListFor(m => m.Points, new SelectList(Model.Points, "PointId", "PointName", Model.Points), "Alle pladser")

This also solved my original problem when clikcing the "Submit" button!
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now