Home > database >  No parameterless constructor defined for this object in MVC 5 while creating identity roles
No parameterless constructor defined for this object in MVC 5 while creating identity roles

Time:01-21

I am developing ASP.NET MVC 5 application for which i need Role-based authorization. While creating the new role i encounter error "No parameterless constructor defined for this object". Even tough i have defined the constructer.

Here is my RoleController

public class RoleController : Controller
{
    private ApplicationRoleManager _roleManager;

    public RoleController()
    {
    }


    public RoleController(ApplicationRoleManager roleManager)
    {
        RoleManager = roleManager;
    }

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }
    // GET: Role
    public ActionResult Index()
    {
        List<RoleViewModel> list = new List<RoleViewModel>();
        foreach (var role in RoleManager.Roles)
            list.Add(new RoleViewModel(role));
        return View(list);
    }
    

    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public async Task<ActionResult> Create(RoleViewModel model)
    {
        var role = new ApplicationRole() { Name = model.Name };
        await RoleManager.CreateAsync(role);
        return RedirectToAction("Index");
    }
}

Here is my RoleViewModel Class

public class RoleViewModel
{
    public RoleViewModel (ApplicationRole role)
    {
        Id = role.Id;
        Name = role.Name;

    }
    public string Id { get; set; }
    public string Name { get; set; }

}

Here is my error message and stack trace

No parameterless constructor defined for this object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

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) 142 System.Activator.CreateInstance(Type type, Boolean nonPublic) 107 System.Activator.CreateInstance(Type type) 13 System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 271

[MissingMethodException: No parameterless constructor defined for this object. Object type 'DivComm.Models.RoleViewModel'.] System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 345 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 750 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) 446 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) 137 System.Web.Mvc.Async.<>c__DisplayClass3_1.b__0(AsyncCallback asyncCallback, Object asyncState) 1082 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) 163 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) 463 System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) 48 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) 73 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) 163 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) 787 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) 163 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) 630 System.Web.Mvc.<>c.b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) 99 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) 73 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) 163 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) 544 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 965 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) 172 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

CodePudding user response:

Seems the issue is comming from ApplicationRole clase. No parameterless constructor defined for ApplicationRole. It is --

public class ApplicationRole
{
    public ApplicationRole (string name)
    {        
        Name = name;
    }
   //----- Properties

}

So your create post action will be --

[HttpPost]
public async Task<ActionResult> Create(RoleViewModel model)
{
    var role = new ApplicationRole(model.Name) { Name = model.Name };
    await RoleManager.CreateAsync(role);
    return RedirectToAction("Index");
}

and your View Model--

public class RoleViewModel
{
    public RoleViewModel ()
    {

    }
    public RoleViewModel (ApplicationRole role)
    {
        Id = role.Id;
        Name = role.Name;

    }
    public string Id { get; set; }
    public string Name { get; set; }

}

Hopefully, it will be helpful.

  • Related