I am creating a MVC4 application and I have got some troubles when I try to get back a form from my view to my controller.
I read several SO post on the topic but unfortunately, I did not managed to find which object does not have a parameterless constructor. All my model classes have a no parameter constructor. And in debug the error stack is just in Internet Explorer but nothing happen in visual studio.
This is the error stack :
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) +117
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +247
System.Activator.CreateInstance(Type type, Boolean nonPublic) +106
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +243
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +151
System.Web.Mvc.DefaultModelBinder.UpdateCollection(ControllerContext controllerContext, ModelBindingContext bindingContext, Type elementType) +545
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +609
System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +33
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +497
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +283
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +677
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +489
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +153
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +883059
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag) +27
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +50
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +869289
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +391
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__3(AsyncCallback asyncCallback, Object asyncState) +827094
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +137
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +167
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag) +27
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +283
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +19
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +161
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +405
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
My Model classes :
public class Form
{
public Form()
{
this.Rows = new List<Row>();
}
public List<Row> Rows { get; set; }
}
public class Row
{
protected Row()
{
this.Label = string.Empty;
this.Type = string.Empty;
}
public string Label { get; set; }
public string Type { get; set; }
}
public class SimpleRow : Row
{
public SimpleRow()
{
this.Value = string.Empty;
}
public string Value { get; set; }
}
public class DropDownRow : Row
{
public DropDownRow()
{
this.Content = new List<ContentDropDown>();
}
public List<ContentDropDown> Content { get; set; }
}
public class ContentDropDown
{
public ContentDropDown()
{
this.Title = string.Empty;
this.Selected = false;
}
public string Title { get; set; }
public bool Selected { get; set; }
}
This can also happen if your underlying class is defined to accept parameter. Since MVC is unable to pass the right value it fails. Try declare a parameter-less class as well. This solved my problem during button click postback.
Eg:
public class Employee
{
public int EmployeeID {get;set;}
public string EmployeeName {get;set;}
public int CostCenter {get;set;}
public DateTime StartDate {get;set;}
public Employee(int employeeID)
{
//Initialize values
}
//Also include a parameter-less construct like below
public Employee()
{
}
}
The default constructor on your Row class is protected. Try changing it to public.
Related
I have been trying to setup DI with Microsoft.Extensions.DependencyInjection for asp.net mvc framework 5.2.7 and it seems to kinda work, since i can see my own services being resolved for the controllers when i debug. Afterwards however it will throw a 'NullReferenceException' and print the following stacktrace:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.FilterProviderCollection.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +127
System.Web.Mvc.ControllerActionInvoker.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +37
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +193
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
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) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
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) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
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) +427
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() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
Global.asax.cs:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
DependencyInjectionConfig.SetDependencyResolver();
}
}
Set Resolver:
public class DependencyInjectionConfig
{
public static void SetDependencyResolver()
{
var services = new ServiceCollection();
services.AddTransient<ITestService, TestService>();
AddControllersAsServices(services, typeof(DependencyInjectionConfig).Assembly.GetExportedTypes()
.Where(t => !t.IsAbstract && !t.IsGenericTypeDefinition)
.Where(t => typeof(IController).IsAssignableFrom(t)
|| t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)));
var serviceProvider = services.BuildServiceProvider();
var dependencyResolver = new Logic.DependencyInjection.DependencyResolver(serviceProvider);
System.Web.Mvc.DependencyResolver.SetResolver(dependencyResolver);
}
public static IServiceCollection AddControllersAsServices(IServiceCollection services, IEnumerable<Type> controllerTypes)
{
foreach (var type in controllerTypes)
{
services.AddTransient(type);
}
return services;
}
}
My DependencyResolver:
public class DependencyResolver : IDependencyResolver
{
private readonly IServiceProvider serviceProvider;
public DependencyResolver(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public object GetService(Type serviceType)
{
var service = this.serviceProvider.GetService(serviceType);
return service;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return new List<object> { GetService(serviceType) };
}
}
The problem is likely in your GetServices implementation:
public IEnumerable<object> GetServices(Type serviceType)
{
return new List<object> { GetService(serviceType) };
}
This doesn't follow the contract, because GetServices should never return a collection with elements that are null, while you are always returning a one-element collection where that element could be null.
Instead, the implementation should likely be something as follows:
public IEnumerable<object> GetServices(Type serviceType)
{
return this.serviceProvider.GetServices(serviceType);
}
I am getting No parameterless constructor defined for this object error while posting data. It is working fine on get. I am using service pattern in my project and using unity container for handling dependency injection. I have registered all the services in container.
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) +122
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +239
System.Activator.CreateInstance(Type type, Boolean nonPublic) +85
System.Activator.CreateInstance(Type type) +12
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +197
[MissingMethodException: No parameterless constructor defined for this object. 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) +285
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +284
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) +377
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) +1210
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +333
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +336
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState) +640
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) +346
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
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) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
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) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
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) +427
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() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
As suggested in some articles i have also created the constructor for my model but no luck.
My Controller (GET)
[HttpGet]
public ActionResult Home()
{
var ct = _ctService.getctdetails();
var viewModel = new HomeviewModel()
{
itemsList= GetItemsList(),
ctDTO= ct
};
return View(viewModel);
}
POST:-
[HttpPost]
public ActionResult Submit(HomeviewModel values)
{
return RedirectToAction("Index");
}
ViewModel:-
public class HomeviewModel
{
public productDetailsDTO { get; set; }
public CreationDTO ctDTO{ get; set; }
public SelectList itemsList{ get; set; }
}
Controller Constructor
public HomeController(ICTService ctService,
ITemsService itemService)
{
_ctService= ctService;
_itemService= itemService;
}
In My view i am just using the itemslist and setting values in DTO , fetching some data using ajax if we change the selected item and submitting form, the control is coming to the controller constructor but after that giving error,not going to the post method.
use Castle.Windsor :
private readonly IIocManager _iocManager;
ICTService _ctService= _iocManager.TryResolve<ICTService>() ??
throw new UserFriendlyException("UnknownActionType");
ITemsService _itemService= _iocManager.TryResolve<ITemsService>() ??
throw new UserFriendlyException("UnknownActionType");
public HomeController()
{
}
in asp.net mvc controller you must add constructor without parameters.
You should add this constructor :
public HomeController()
{
_ctService= new ICTService() ;
_itemService= new ITemsService() ;
}
I Have an Asp.Net MVC 4 Application and I'm using Simple Injector, I configured everything my application starts whell but when I try to post an exemplo form (when system will need the injection) is says "No constructor parametherless defined" to this object. It means that the injections is not working, but I think all is configured fine.
SimpleInjectorInitializer class:
[assembly: WebActivator.PostApplicationStartMethod(typeof(SimpleInjectorInitializer), "Initialize")]
public static class SimpleInjectorInitializer
{
public static void Initialize()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
InitializeContainer(container);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}
private static void InitializeContainer(Container container)
{
SimpleInjectorContainer.RegisterContainer(container);
}
}
Container class (Where a register my dependencies)
public static class SimpleInjectorContainer
{
public static void RegisterContainer(Container container)
{
container.RegisterPerWebRequest<IPessoaRepository, PessoaRepository>();
}
}
I already have the assemblies:
SimpleInjector
SimpleInjector.Integration.Web
SimpleInjector.Integration.Web.Mvc
StackTrace
MissingMethodException: Nenhum construtor sem parĂ¢metros foi definido para este objeto.]
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) +114
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) +197
[MissingMethodException: Nenhum construtor sem parĂ¢metros foi definido para este objeto. Tipo de objeto 'Cerocha.Domain.Entities.Pessoa'.]
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +233
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +531
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +330
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +330
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() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
You are trying to inject dependencies into your view model object. This is something that is not supported by MVC by default and not supported by the Simple Injector integration package, because it is a bad idea to mix runtime data with dependencies.
Your view models should not contain any behavior. Once you separate data and behavior, tou don't need to inject dependencies into view models and your problem will dissappear.
While trying to submit a form with file upload/multiple file upload/form fields/checkbox I get the above error. I have gone through various resources on SO but could not identify the problem. Here's my stack trace below:
[ArgumentException: An item with the same key has already been added.]
System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +10925834
System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value) +10
System.Collections.Generic.CollectionExtensions.ToDictionaryFast(TValue[] array, Func`2 keySelector, IEqualityComparer`1 comparer) +209
System.Web.Mvc.ModelBindingContext.get_PropertyMetadata() +201
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +387
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +180
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +106
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2541
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +633
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +494
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +199
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1680
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +559
System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588
System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +484
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +446
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I properly went through my model and my ViewModel, I didn't find any duplication in properties. Here's my ViewModel:
public class ArticlesViewModel
{
public ArticlesViewModel()
{
Teams = new List<TeamVM>();
}
public string gameName { get; set; }
public List<TeamVM> Teams { get; set; }
[Required]
[DisplayName("Article Content")]
public string articleContent { get; set; }
public System.DateTime date { get; set; }
[Required]
[DisplayName("Article Title")]
public string articleTitle { get; set; }
[ValidateFile]
[Display(Name = "FeaturedImage")]
public HttpPostedFileBase featuredImage { get; set; }
[ValidateFile]
[Display(Name = "Picture Gallery Image(s)")]
public IEnumerable<HttpPostedFileBase> picturePath { get; set; }
// properties for the articles, game, gallery and teams respectively
public gallery mgallery { get; set; }
public TeamVM teams { get; set; }
}
And here is the controller action for the viewmodel:
namespace TeamBuildingCompetition.Areas.Admin.Controllers
{
public class ArticlesController : BaseAdminController
{
// GET: Admin/Articles
TBCDBEntities db;
public ArticlesController()
{
db = new TBCDBEntities();
}
[HttpGet]
public ActionResult Index()
{
ArticlesViewModel model = new ArticlesViewModel();
var teamList = (from p in db.teams
select new TeamVM()
{
teamID = p.teamID,
TeamName = p.teamName,
IsSelected = p.IsSelected
});
model.Teams = teamList.ToList();
ViewBag.gameList = new SelectList(db.games, "gameID", "gameName");
return View(model);
}
[HttpPost]
public ActionResult Create(ArticlesViewModel model)
{
try
{
// Get the featured file name
string featuredFileName = Path.GetFileName(model.featuredImage.FileName);
// Get the featured file path
string path = Path.Combine(Server.MapPath("~/Content/Upload"), featuredFileName);
// Get the path that will be saved into the database
string imgDBPath = "~/Content/Upload/" + featuredFileName.ToString();
// Save the featured images to the folder
model.featuredImage.SaveAs(path);
// Declare the picture gallery file path names
var getFileNames = "";
var getGalleryPath = "";
var getGalleryImgPath = "";
// Iterate through each file in the collection
foreach (var item in model.picturePath)
{
getFileNames = Path.GetFileName(item.FileName); // Get the file names
getGalleryPath = Path.Combine(Server.MapPath("~/Content/Upload"), getFileNames); // Get the file paths
getGalleryImgPath = "~/Content/Upload/" + getFileNames.ToString(); // Get the file path to be stored in the database
item.SaveAs(getGalleryPath); // Save the each file in the upload directory
}
// Map article properties with values
article objArticle = new article
{
featuredImage = imgDBPath,
articleTitle = model.articleTitle,
articleContent = model.gameName,
date = DateTime.Now,
lastupdated = DateTime.Now
};
// Map gallery properties with values
gallery objGallery = new gallery
{
gameID = model.mgallery.gameID,
teamID = model.teams.teamID,
picturePath = model.picturePath.ToString()
};
// Insert the article/gallery picture into the database
objBs.articleBs.Insert(objArticle);
objBs.galleryBs.Insert(objGallery);
TempData["Msg"] = "Created Successfully!";
return RedirectToAction("Index");
}
catch (DbEntityValidationException dbEx)
{
var sb = new StringBuilder();
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
sb.AppendLine(string.Format("Entity:'{0}' Property: '{1}' Error: '{2}'",
validationErrors.Entry.Entity.GetType().FullName,
validationError.PropertyName,
validationError.ErrorMessage));
}
}
//throw new Exception(string.Format("Failed saving data: '{0}'", sb.ToString()), dbEx);
TempData["Msg"] = sb.ToString();
return RedirectToAction("Index");
}
}
}
}
And whenever I remove ArticlesViewModel model from public ActionResult create(ArticlesViewModel model) of the controller, I get null reference error.
You have both
public List<TeamVM> Teams { get; set; }
and
public TeamVM teams { get; set; }
While this is valid C#, you have two properties with the same name (if you don't take case into account).
Just change their names.
edit: I'm not sure how I missed this previously, but this might be a duplicate of Binding a dictionary containing a list in MVC4.
I'm using ASP.NET MVC4, and I have a dictionary property that is keyed on an enum and has a class as its value type. I'm using Html.TextBoxFor to generate the HTML for a form to a controller action that takes one of these as the view model. I get an InvalidCastException during binding when I submit the form through my browser.
Here's the view model:
public class MyViewModel
{
public virtual IDictionary<MyEnumType, IList<MySubViewModel>> Subs { get; set; }
public class MySubViewModel
{
public virtual String Name { get; set; }
}
}
In the controller, I have:
[HttpGet]
public ActionResult EditPage(Int32? id)
{
MyViewModel testViewModel = new MyViewModel
{
Subs = new Dictionary<MyEnumType, IList<MyViewModel.MySubViewModel>>() {
{
MyEnumType.MySubViewModel
, new List<MyViewModel.MySubViewModel> {
new MyViewModel.MySubViewModel {
Name = "Foo-Bar"
}
}
}
}
};
return View(testViewModel);
}
[HttpPost]
public ActionResult EditPage(MyViewModel model)
{
return View(model);
}
I have in my view (using the Spark view engine):
<tbody each="var enumValue in Html.EnumValues<MyEnumType>()">
<tr each="var sub in Model.Subs[enumValue]" class="DataRow">
<td>
${Html.TextBoxFor(m => m.Subs[enumValue][subIndex].Name, new { #class="SubName" })}
</td>
</tr>
</tbody>
This gets rendered as:
<tbody>
<tr>
<td>
<input id="Subs_EnumValueOne__0__Name" type="text" value="Foo-Bar" name="Subs[EnumValueOne][0].Name">
</td>
</tr>
</tbody>
When I submit the page, I get an InvalidCastException: {"Specified cast is not valid."}.
at System.Web.Mvc.DefaultModelBinder.CollectionHelpers.ReplaceDictionaryImpl[TKey,TValue](IDictionary`2 dictionary, IEnumerable`1 newContents)
Here's the stack trace. (I have a model binder for a different type, but for this dictionary property, it simply passes through to base.BindModel.)
[InvalidCastException: Specified cast is not valid.]
System.Web.Mvc.CollectionHelpers.ReplaceDictionaryImpl(IDictionary`2 dictionary, IEnumerable`1 newContents) +131
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +92
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +108
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
System.Web.Mvc.CollectionHelpers.ReplaceDictionary(Type keyType, Type valueType, Object dictionary, Object newContents) +178
System.Web.Mvc.DefaultModelBinder.UpdateDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type keyType, Type valueType) +1211
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +921
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +416
Namespace.For.MyBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1195
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
Namespace.For.MyBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1195
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) +382
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) +15
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
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
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
It looks like you forget to re-populate the Subs property of your MyViewModel in the POST action. You have to do that in both the GET and POST request.
You could refactor it to a method and call it in both actions:
private Dictionary<MyEnumType, IList<MyViewModel.MySubViewModel>> GetSubsDict()
{
return new Dictionary<MyEnumType, IList<MyViewModel.MySubViewModel>>()
{
{
MyEnumType.MySubViewModel,
new List<MyViewModel.MySubViewModel>
{
new MyViewModel.MySubViewModel
{
Name = "Foo-Bar"
}
}
}
}
}
The GET action:
public ActionResult EditPage(Int32? id)
{
MyViewModel testViewModel = new MyViewModel
{
Subs = GetSubsDict();
}
return View(testViewModel);
}
And in the POST action again:
public ActionResult EditPage(MyViewModel model)
{
model.Subs = GetSubsDict();
return View(model);
}