简体   繁体   中英

No parameterless constructor defined for this object in mvc

When I use SelectList in View then i get error "No parameterless constructor defined for this object", I saw many solutions but unable to find that work for me. This is view code:

@using (Html.BeginForm("Product", "Products", FormMethod.Post, new { @class = "form-horizontal" }))
{
   @Html.ValidationSummary()

   <div class="form-group">
       <label class="control-label col-md-3" for="SelectProduct">Select Product</label>
       <div class="col-md-4">
           @Html.DropDownListFor(p => p.SelectProduct, new SelectList(new[] 
           {
             new { Value = "New", Text = "New Entry" },
             new { Value = "Existing", Text = "Existing Entry" },
           }, "Value", "Text"), 
           new { @class = "form-control" })
       </div>
   </div> 
   <div class="form-group">
       <label class="control-label col-md-3" for="productName">Product Name</label>
       <div class="col-md-8">
          @Html.TextBoxFor(u => u.ProductName, new { @class = "form-control", @id = "productName" })
       </div>
   </div>   
}

Controller:

[HttpPost]
public ActionResult Product(ProductDto model)
{
    //code here
}

Model:

public class ProductDto
{
    public ProductDto()
    {
    }
    /// <summary>
    /// Gets or sets whether its New or existing product
    /// </summary>
    public SelectList SelectProduct { get; set; }


    /// <summary>
    /// Gets or sets product name.
    /// </summary>
    public string ProductName { get; set; }

}

Stack Trace:

[MissingMethodException: No parameterless constructor defined for this  object.]
       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) +119
      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) +11
     System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +183
    System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +329
     System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +368
     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) +384
      System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +88
                  System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +53
         System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1314
        System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +416
      System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
         System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
       System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
       System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
       System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
    System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
      System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
  System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +381
       System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
      System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
        System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +17
       System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
   System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130

Thanks

DropDownListFor is meant to set a value on a property in your model - your model contains a SelectProduct property which is of type SelectList - I'm guessing it should be of type string since that's the type of the Value property of the SelectList you're building in the view.

public class ProductDto
{
    public ProductDto()
    {
    }
    /// <summary>
    /// Gets or sets whether its New or existing product
    /// </summary>
    public string SelectProduct { get; set; }


    /// <summary>
    /// Gets or sets product name.
    /// </summary>
    public string ProductName { get; set; }

  }

Note that a purer method would be to build the SelectList in the controller or ViewModel rather than in the view. That way you separate the logic of building the possible values form the view itself.

If SelectList that you use in ProductDto class is System.Web.Mvc.SelectList then it is the cause of your problem. System.Web.Mvc.SelectList does not have parameterless constructor.

@Html.DropDownListFor(p => p.SelectProduct, new SelectList(new[] 

you should change this code.

@Html.DropDownListFor(p => p.SelectProductID, new SelectList(new[] 

I used SelectProductID because when you want to use. It will fill with Models.

So you can selecy only one item your dropdownlist.

I hope this is usefull for you.

Thanks.

This Code Will Help You. Use This Method .

Htmlcs

@model OspWebsite.Models.bcEvent             
@using (Html.BeginForm())  
@Html.AntiForgeryToken()
  @Html.ValidationSummary(true)
<div class="col-4 ">

    @Html.LabelFor(model => model.eventCountry, new { @class = "col-sm-6  control-label" })   //For Label
    @Html.DropDownList("FeedBack", ViewData["dropdownCountry"] as List<SelectListItem>)     //For DropDown 

 </div>
}

MngClass...

public class MngEvent
{
public DataTable ShowEvent()
    {
        try
        {
          SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ospDB"].ConnectionString);

            SqlCommand cmd = new SqlCommand("usp_SelectAllConfrence", con);
            SqlDataAdapter sda = new SqlDataAdapter();
            DataTable dt = new DataTable();
            cmd.CommandType = CommandType.StoredProcedure;
            if (con.State.Equals(ConnectionState.Closed))
                con.Open();
            sda.SelectCommand = cmd;
            sda.Fill(dt);
            con.Close();
            return dt;

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  }

Controller...

   public class AdminEventsController : Controller
   {
    [HttpGet]
    public ActionResult addEvent()
    {   
        ////ComboBox Country
        List<SelectListItem> lst = new List<SelectListItem>();
        MngEvent events = new MngEvent();
        DataTable dt1 = events.ShowEvent();
        for (int i = 0; i <= dt1.Rows.Count; i++)
        {
            lst.Add(new SelectListItem { Text = dt1.Rows[i]["ConfrenceCountry"].ToString(), Value = dt1.Rows[i]["ConfrenceID"].ToString() });
        }
        ViewData["dropdownCountry"] = lst;
        return View();
    }
 }

If Any Problem Feedback. Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM