In my application I have a page that displays a list of records and with every record there is a link to click for more details of that record. It goes to the other controller.
Let me tell a sequence. From 'ToDoListSelect' controller it goes to 'ToDoList' and on clicking the link from ToDoList it goes to 'Info' controller. Everything works fine on my development machine with same database as on the server.
Now, I put the package on server and there it works okay if the records on the page are less than 500 or so. If there are more records then from ToDoList it does not go to Info but throws exception and I see it's going to ToDoListSelect which is weird. I do not know where to start looking for the problem. Any suggestions? Any details needed just let me know.
Here are the routes in my application:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( "Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
The error thrown is:
Server Error in '/' Application.
The operation is invalid because of the current state of the object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about this error, view and determine where the error originated in the code.
Exception Details: System.InvalidOperationException: Operation is not valid due to the current state of the object.
Source Error:
During execution of the current web request An unhandled exception was generated. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
[InvalidOperationException: Der Vorgang ist aufgrund des aktuellen Zustands des Objekts ungültig.]
System.Web.HttpRequest.FillInFormCollection() +11485999
System.Web.HttpRequest.get_Form() +157
Microsoft.Web.Infrastructure.DynamicValidationHelper.<>c__DisplayClass12.<ReplaceCollection>b__e() +63
Microsoft.Web.Infrastructure.DynamicValidationHelper.<>c__DisplayClass12.<ReplaceCollection>b__11() +20
Microsoft.Web.Infrastructure.DynamicValidationHelper.DeferredCountArrayList.get_Count() +20
System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +34
System.Web.HttpRequest.get_Form() +212
System.Web.Mvc.FormValueProvider..ctor(ControllerContext controllerContext, IUnvalidatedRequestValues unvalidatedValues) +55
System.Web.Mvc.FormValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +61
System.Web.Mvc.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) +28
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +238
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +148
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +472
System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +347
System.Web.Mvc.ControllerBase.get_ValueProvider() +46
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +80
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +153
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +691
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +305
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
Figured it out! Thanks Mr. Google!
http://geekswithblogs.net/renso/archive/2012/01/19/operation-is-not-valid-due-to-the-current-state-of.aspx
Put the change in web.config and it works fine.
Related
using Michell.ClaimsAuditAdmin.Models;
using Mitchell.ClaimsAuditAdmin.Repositories;
using Mitchell.ClaimsAuditAdmin.Web.Models;
using System.Web.Mvc;
namespace Mitchell.ClaimsAuditAdmin.Web.Controllers
{
public class ClaimAuditAdminController : Controller
{
private readonly IClaimsAuditAdminRepository claimAuditAdminRepository;
public ClaimAuditAdminController(IClaimsAuditAdminRepository claimAuditAdminRepository)
{
this.claimAuditAdminRepository = claimAuditAdminRepository;
}
public ActionResult Index()
{
return View("SearchResultTest");
}
public ActionResult TestView()
{
return View("TestView");
}
public ViewResult DisplayClaimAuditView()
{
return View("_ClaimAuditAdminView");
}
public ActionResult SearchResultTest()
{
return View();
}
public ActionResult ClaimAuditReviewFilter()
{
//ClaimAuditModel objClaimAudit = new ClaimAuditModel();
//objClaimAudit.ClaimAudit_ID = 1;
//objClaimAudit.ClaimAudit_Name = "Claim1";
//objClaimAudit.FromDate = DateTime.Now.AddYears(-1);
//objClaimAudit.FromDate = DateTime.Now;
return PartialView("_ClaimAuditAdminView");
}
}
}
I know this question has been asked many times,but after reading all those SO similar questions i am not able to track my error.I have put the debugger in My controller's Constructor(ClaimAuditAdminController) but debugger doesn't goes there.
My Route.Config is
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ClaimAuditAdmin", action = "DisplayClaimAuditView", id = UrlParameter.Optional }
);
}
and the screen shot of my error is
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) +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.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a
controller of type
'Mitchell.ClaimsAuditAdmin.Web.Controllers.ClaimAuditAdminController'.
Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +179
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext
requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
+197 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +49
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
-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.17929
}
activator trying to create ur controller with parametrless constructor. but while your controller constructor has parameter
public ClaimAuditAdminController(IClaimsAuditAdminRepository claimAuditAdminRepository) <--this place
{
this.claimAuditAdminRepository = claimAuditAdminRepository;
}
the exception occurs.
Try to remove param from constructor or try override the DefaultControllerFactory
and create controller with parameter.
look here
I've searched the internet high and low and checked all previously answered questions with the same title and I cannot figure this one out.
I return RedirectToAction("Index", "Home") from the action method in my authentication controller and then receive the following exception:
Server Error in '/' Application.
The controller for path '/Home' was not found or does not implement IController.
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.Web.HttpException: The controller for path '/Home' was not found or does not implement IController.
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:
[HttpException (0x80004005): The controller for path '/Home' was not found or does not implement IController.]
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +683921
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +89
Castle.Proxies.Invocations.IControllerFactory_CreateController.InvokeMethodOnTarget() +155
Castle.DynamicProxy.AbstractInvocation.Proceed() +116
Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +85
Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +186
Castle.DynamicProxy.AbstractInvocation.Proceed() +604
Castle.Proxies.IControllerFactoryProxy.CreateController(RequestContext requestContext, String controllerName) +193
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +305
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +87
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +41
[HttpException (0x80004005): Execution of the child request failed. Please examine the InnerException for more information.]
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +785832
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3977
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +275
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +94
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +700
System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +123
Panoptes.Ui.Web.Views.Home.Index.Execute() in c:\Dropbox\Energy Management System\Application\Panoptes\Panoptes.Ui.Web\obj\CodeGen\Views\Home\Index.cshtml:48
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +126
System.Web.WebPages.StartPage.ExecutePageHierarchy() +143
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +181
RazorGenerator.Mvc.PrecompiledMvcView.Render(ViewContext viewContext, TextWriter writer) +952
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +378
Castle.Proxies.AsyncControllerActionInvokerProxy.InvokeActionResult_callback(ControllerContext controllerContext, ActionResult actionResult) +21
Castle.DynamicProxy.AbstractInvocation.Proceed() +116
Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +85
Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +186
Castle.DynamicProxy.AbstractInvocation.Proceed() +604
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +33
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +854172
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +854172
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +838644
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18034
The authentication controller looks as follows:
public class AuthenticationController : Controller
{
private ILogService _logService;
private IEmailProvider _emailProvider;
private IMembershipProvider _membershipProvider;
private IAuthenticationProvider _authenicationProvider;
public AuthenticationController(ILogService logService, IEmailProvider emailProvider, IMembershipProvider membershipProvider, IAuthenticationProvider authenicationProvider)
{
_logService = logService;
_emailProvider = emailProvider;
_membershipProvider = membershipProvider;
_authenicationProvider = authenicationProvider;
}
[AllowAnonymous]
[HttpGet]
////[OutputCache(Duration = 3600, VaryByParam = "none")]
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[HttpPost]
[ValidateHttpAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (Request.IsAuthenticated)
{
return RedirectToAction("Index", "Home");
}
if (ModelState.IsValid)
{
if (_membershipProvider.ValidateUser(model.Username, model.Password))
{
_authenicationProvider.AuthenticateUser(model.Username);
////this.HttpContext.User = new GenericPrincipal(new GenericIdentity(model.Username), null);
if (!string.IsNullOrEmpty(returnUrl))
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
_logService.Log(new SecurityException(string.Format("Open redirect to {0} detected (Username {1})", returnUrl, model.Username)));
return View("Index", model);
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError(string.Empty, Resources.Controller.View.Authentication.Index.IncorrectUsernamePassword);
}
}
return View("Index", model);
}
[AllowAnonymous]
[HttpPost]
[ValidateHttpAntiForgeryToken]
public ActionResult ForgotPassword(LoginModel model)
{
if (ModelState.IsValidField("Username"))
{
if (!_membershipProvider.EnablePasswordRetrieval)
{
throw new Exception(Resources.Controller.View.Authentication.Index.PasswordRetreivalNotAllowed);
}
IMembershipUser user = _membershipProvider.FindUsersByName(model.Username).FirstOrDefault();
if (user != null)
{
try
{
_emailProvider.Send(ConfigurationHelper.GetSmtpSettings().Smtp.From, user.EmailAddress, Resources.Global.PasswordRecoveryEmailSubject, user.GeneratePasswordRetreivalEmail());
ModelState.AddModelSuccess(Resources.Controller.View.Authentication.Index.PasswordSentViaEmail);
}
catch (Exception ex)
{
_logService.Log(ex);
ModelState.AddModelError(string.Empty, Resources.Controller.View.Authentication.Index.UnableToRetreivePassword);
}
}
else
{
ModelState.AddModelError(string.Empty, Resources.Controller.View.Authentication.Index.EmailAddressDoesNotExist);
}
}
ViewBag.ShowForgottenPasswordForm = "true";
return View("Index", model);
}
[HttpGet]
public ActionResult Logout()
{
_authenicationProvider.Logout();
ModelState.AddModelInformation(Resources.Controller.View.Authentication.Index.Logout);
return View("Index");
}
}
My HomeController looks as follows:
public class HomeController : Controller
{
private IMembershipProvider _membershipProvider;
private IAuthenticationProvider _authenticationProvider;
public HomeController(IMembershipProvider membershipProvider, IAuthenticationProvider authenticationProvider)
{
_membershipProvider = membershipProvider;
_authenticationProvider = authenticationProvider;
}
public ActionResult Index()
{
return View(_membershipProvider.GetCurrentUser());
}
}
See below my RouteConfig:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Authentication", action = "Index" });
}
}
RouteDebugger returns TRUE for the routes {controller}/{action} and {*catchall} and confirms the AppRelativeCurrentExecutionFilePath as: ~/Home
I have debugged the code and I can successfully debug and step into the HomeController constructor and Index action method. I have also been able to step into the "~/Views/Home/Index.cshtml" however it throws the exception at the line of code:
<span class="username">#Model.UserName</span>
Funnily enough, before I step into this code I can add "#Model.UserName" to my list of watches and I can see the object and its properties fine, but for some reason it throws an exception when stepping into or over this line of code.
If the debugger steps into the HomeController, the Index action method and the Index view, then why is it all of a sudden throwing the exception it can't find the HomeController for the path "~/Home"?
The captured fiddler data can be found at the following link: http://d-h.st/IqV
I have used Razor Generator to compile my views and I am also using Ninject.Mvc to resolve my controllers. It's also worth mentioning I have cleared down and re-generated the compiled views and my project does not contain any registered areas.
Any idea's? this might be simple or an obvious one but I'm new to MVC and am reading/learning as I go.
Thanks
So people can see this question was answered here is why it was throwing the exception and how I fixed it:
The exception was being thrown because of the following line of code in the HomeController Index view:
<i class="icon-key"></i> Log Out
As you can see it's passing the wrong arguments and "Log Out" is being passed in as the action name when infact this should be "Logout". I correct it to the following and it worked:
<i class="icon-key"></i> Log Out
So if you're getting this exception and like me can't understand why then please make sure you check the rest of your code in your view to make sure it is correct. In this instance the framework doesn't provide a meaning exception message and stacktrace.
Occasionally (about once a month) an ASP.NET MVC 3 web application fails with this exception.
System.NullReferenceException: Object reference not set to an instance of an object.
Server stack trace:
at System.Collections.Specialized.NameObjectCollectionBase.BaseGetAllKeys()
at System.Collections.Specialized.NameValueCollection.get_AllKeys()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.<>c__DisplayClass4.<.ctor>b__0()
at System.Lazy`1.CreateValue()
Exception rethrown at [0]:
at System.Lazy`1.get_Value()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value)
at System.Web.Mvc.ViewContext.ScopeGet[TValue](IDictionary`2 scope, String name, TValue defaultValue)
at System.Web.Mvc.ViewContext.ScopeCache..ctor(IDictionary`2 scope)
at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.ViewContext.GetClientValidationEnabled(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.Html.FormExtensions.FormHelper(HtmlHelper htmlHelper, String formAction, FormMethod method, IDictionary`2 htmlAttributes)
at ASP._Page_Views_mywebpage_Create_cshtml.Execute() in c:\App\Views\Mywebpage\Create.cshtml:line 11
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This exception occurs on a line with
#using (Html.BeginForm())
From the moment this exception occurs once, the application is unusable. Every view will start throwing this error. I've looked around in the source code but seem unable to find anything. There are people who experience the same behaviour but with a different error and or by different code.
When digging deeper in the source of WebConfigScopeDictionary you can see that the AppSettings are being read:
public WebConfigScopeDictionary() : this(WebConfigurationManager.AppSettings)
{
}
public WebConfigScopeDictionary(NameValueCollection appSettings)
{
this._items = new Lazy<Dictionary<object, object>>(() => appSettings.AllKeys.ToDictionary((string key) => key, (string key) => appSettings[key], ScopeStorageComparer.Instance));
}
The appsettings come from the ConfigurationManager:
public static NameValueCollection AppSettings
{
get
{
object section = ConfigurationManager.GetSection("appSettings");
if (section == null || !(section is NameValueCollection))
{
throw new ConfigurationErrorsException(SR.GetString("Config_appsettings_declaration_invalid"));
}
return (NameValueCollection)section;
}
}
If there would be a problem with the web.config this code should have thrown an exception. But it doesn't. Eventually count is called on the collection that is returned by the AppSettings property. Since it is probably null at this point it throws.
protected string[] BaseGetAllKeys()
{
int count = this._entriesArray.Count;
string[] array = new string[count];
for (int i = 0; i < count; i++)
{
array[i] = this.BaseGetKey(i);
}
return array;
}
If anyone has any ideas, feel free to share.
After enquiring with the ops team it would appear that the application pool was being recycled after the timed interval had expired. This happened during office hours while the application is under a significant load. We've now changed it to recycle at a specific time, which is still a workaround but should prevent the problem from occurring too frequently.
I have serious problem I can not pass my data to controller when the form submitted how I can solve this ?
//int controller class
[HttpPost]
public ActionResult Index(EnterpriseFramework.Entity.Synchronization.BindableEntity model)
{
//do something
}
and my view :
#model EnterpriseFramework.Entity.Synchronization.BindableEntity
<p>
#using (Html.BeginForm())
{
<fieldset>
<legend>title</legend>
<div>
#Html.HiddenFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Id)
</div>
<div>
#Html.LabelFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Number)
#Html.TextBoxFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Number)
</div>
<div>
#{
EnterpriseFramework.Entity.Synchronization.DataSource ds = Model.GetRelation("lnkLetterReceiver");
foreach (EnterpriseFramework.Entity.Synchronization.BindableEntity item in ds)
{
AutomationTest.Models.DTO.LetterReceiver childRece = item.Underlay.Entity as
AutomationTest.Models.DTO.LetterReceiver;
<div>
#Html.LabelFor(c=> childRece.oau_LetterReceiver_Name)
#Html.TextBoxFor(c=> childRece.oau_LetterReceiver_Name)
</div>
}
}
</div>
<div>
<input type="submit" name="Confirm" value="Confirm" />
</div>
</fieldset>
}
</p>
Server Error in '/' Application.
--------------------------------------------------------------------------------
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) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +199
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +572
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8897857
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Every type that you are trying to use as action parameter must have a default parameterless constructor. Otherwise the default model binder will not be able to instantiate it and populate its properties.
That's why you should never use your domain models in views. You should define and use view models which are classes specifically design to meet the requirements of a given view. Then the controller action will map back and forth between the view models and the domain models. Like this:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// There were validation errors => redisplay the view
return View(model);
}
// the model is valid => map the view model to a domain model and process
...
}
That's as far as best practices are concerned. If your application has already been polluted and refactoring towards view models is not possible at the moment you have two possibilities:
Write a custom model binder for the BindableEntity type so that you manually invoke the proper constructor in the CreateModel method.
Add a default parameterless constructor to the BindableEntity type.
Use the TryUpdateModel method:
[HttpPost]
public ActionResult Index()
{
var model = new BindableEntity(WHATEVER);
if (!TryUpdateModel(model) || !ModelState.IsValid)
{
// There were validation errors => redisplay the view
return View(model);
}
// the model is valid => process
...
}
I assume you have only defined constructors with parameters? To fix this, you need to add this line of code
public BindableEntity()
{ }
To your EnterpriseFramework.Entity.Synchronization.BindableEntity class.
This will define a parameter-less constructor and will allow you to use it as you desire, although you do need to define a ViewModel in order to use MVC in the way it was designed.
This is part of the first build repoistory that sits on Microsoft MVC.
First call from the controller down for model.
public ActionResult Index()
{
var prog = yRepository.FindUpComingProgrammes();
return View(prog);
}
ASP ERROR:
Server Error in '/' Application.
--------------------------------------------------------------------------------
The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Code.Models.Prog]' but this dictionary requires a model item of type 'Code.Models.Prog'.
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.InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Code.Models.Prog]' but this dictionary requires a model item of type 'Code.Models.Prog'.
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:
[InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Linq.DataQuery`1[Code.Models.Prog]' but this dictionary requires a model item of type 'Code.Models.Prog'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +116376
System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +369
System.Web.Mvc.ViewPage`1.SetViewData(ViewDataDictionary viewData) +59
System.Web.Mvc.WebFormView.RenderViewPage(ViewContext context, ViewPage page) +70
System.Web.Mvc.WebFormView.Render(ViewContext viewContext, TextWriter writer) +92
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +278
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +10
System.Web.Mvc.<>c__DisplayClass11.<InvokeActionResultWithFilters>b__e() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +251
System.Web.Mvc.<>c__DisplayClass13.<InvokeActionResultWithFilters>b__10() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +178
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +399
System.Web.Mvc.Controller.ExecuteCore() +126
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +151
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +57
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
It sounds like you are using a strongly typed view and the object being passed to the view is not the same that type that the view is bound to...