0

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)

3
  • Please share the entire error message, including stack trace and inner exceptions, if any. Commented Jan 19, 2023 at 4:29
  • I have updated my question and shared my entire error message, including stack trace – maybe that might be helpful to ascertain the cause of error Commented Jan 19, 2023 at 15:38
  • 1
    The information you provided makes the problem clear now. It's your Create action method. It takes a RoleViewModel as a parameter. However, the MVC model binder is choking because that class needs a parameterless constructor. Commented Jan 20, 2023 at 5:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, the problem persists. I have updated my question and I have shared my entire error message, including stack trace
@Zahid you need to create a parameterless constructor for RoleViewModel as well. I updated my answer as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.