Where is this System.MissingMethodException occurring? How can I tell? - asp.net-mvc

I am a newbie to ASP.NET MVC (v2), and I am trying to use a strongly-typed view tied to a model object that contains two optional multi-select listbox objects. Upon clicking the submit button, these objects may have 0 or more values selected for them.
My model class looks like this:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace ModelClasses.Messages
{
public class ComposeMessage
{
public bool is_html { get; set; }
public bool is_urgent { get; set; }
public string message_subject { get; set; }
public string message_text { get; set; }
public string action { get; set; }
public MultiSelectList recipients { get; set; }
public MultiSelectList recipient_roles { get; set; }
public ComposeMessage()
{
this.is_html = false;
this.is_urgent = false;
this.recipients = new MultiSelectList(new Dictionary<int, string>(), "Key", "Value");
this.recipient_roles = new MultiSelectList(new Dictionary<int, string>(), "Key", "Value");
}
}
}
My view looks like this:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ModelClasses.Messages.ComposeMessage>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Compose A Message
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Compose A New Message:</h2>
<br />
<span id="navigation_top">
<%= Html.ActionLink("\\Home", "Index", "Home") %><%= Html.ActionLink("\\Messages", "Home") %></span>
<% using (Html.BeginForm())
{ %>
<fieldset>
<legend>Message Headers</legend>
<label for="message_subject">
Subject:</label>
<%= Html.TextBox("message_subject")%>
<%= Html.ValidationMessage("message_subject")%>
<label for="selected_recipients">
Recipient Users:</label>
<%= Html.ListBox("recipients") %>
<%= Html.ValidationMessage("selected_recipients")%>
<label for="selected_recipient_roles">
Recipient Roles:</label>
<%= Html.ListBox("recipient_roles") %>
<%= Html.ValidationMessage("selected_recipient_roles")%>
<label for="is_urgent">
Urgent?</label>
<%= Html.CheckBox("is_urgent") %>
<%= Html.ValidationMessage("is_urgent")%>
</fieldset>
<fieldset>
<legend>Message Text</legend>
<%= Html.TextArea("message_text") %>
<%= Html.ValidationMessage("message_text")%>
</fieldset>
<input type="reset" name="reset" id="reset" value="Reset" />
<input type="submit" name="action" id="send_message" value="Send" />
<% } %>
<span id="navigation_bottom">
<%= Html.ActionLink("\\Home", "Index", "Home") %><%= Html.ActionLink("\\Messages", "Home") %></span>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Scripts" runat="server">
</asp:Content>
I have a parameterless ActionResult in my MessagesController like this:
[Authorize]
public ActionResult ComposeMessage()
{
ModelClasses.Messages.ComposeMessage FormData = new ModelClasses.Messages.ComposeMessage();
Common C = (Common)Session["Common"];
FormData.recipients = new MultiSelectList(C.AvailableUsers, "Key", "Value");
FormData.recipient_roles = new MultiSelectList(C.AvailableRoles, "Key", "Value");
return View(FormData);
}
...and my model-based controller looks like this:
[Authorize, AcceptVerbs(HttpVerbs.Post)]
public ActionResult ComposeMessage(ModelClasses.Messages.ComposeMessage FormData)
{
MyUserClass CurrentUser = (MyUserClass )Session["CurrentUser"];
Common C = (Common)Session["Common"];
//... (business logic)
return View(FormData);
}
Problem is, I can access the page fine before a submit. When I actually make selections and press the submit button, however, I get:
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, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +307
System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +495
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +473
System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45
System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +642
System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +144
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +95
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2386
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +539
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +447
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +173
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +801
System.Web.Mvc.Controller.ExecuteCore() +151
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +105
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +36
System.Web.Mvc.<>c__DisplayClass8.b__4() +65
System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult1.End() +140
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +36
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082
This error shows up before I can trap it. I have no idea where it's choking, or what it's choking on. I don't see any point of this model that cannot be created with a parameterless constructor, and I can't find out where it's dying... Help is appreciated, thanks.
-Jeremy

Strongly typing recipients and recipient_roles as MultiSelectList may be causing this problem. Try the following simple mod to your code:
public object recipients { get; set; }
public object recipient_roles { get; set;

Related

The model item passed into the dictionary is of type , but dicitonary requires a model item of type

I am a beginner with ASP.NET MVC and I have a rather weird problem which I can't seem to work out how to fix. I have found multiple solutions to various versions of the same problem via google, but they don't seem to relate to my problem. If anyone would be kind enough to help me spot the mistake I would be grateful.
Edit: I know that changing #model app.Models.Authentication to #model app.Models.ContactMessage will fix it, but I don't understand why and obviously the propsed fix will give me a bunch of other errors related to the form.
My Error: The model item passed into the dictionary is of type 'app.Models.Auth', but this dictionary requires a model item of type 'app.Models.ContactMessage'
Relevant Q&A:
Similar Problem #1
Similar Problem #2
Stack Trace:
[InvalidOperationException: The model item passed into the dictionary is of type 'app.Models.Authentication', but this dictionary requires a model item of type 'app.Models.ContactMessage'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +378
System.Web.Mvc.ViewDataDictionary.set_Model(Object value) +47
System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +259
System.Web.Mvc.ViewDataDictionary`1..ctor(ViewDataDictionary viewDataDictionary) +37
System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +98
System.Web.Mvc.WebViewPage.set_ViewData(ViewDataDictionary value) +39
System.Web.Mvc.WebViewPage.ConfigurePage(WebPageBase parentPage) +267
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +318
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +42
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +45
System.Web.WebPages.WebPageBase.Write(HelperResult result) +53
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +178
System.Web.WebPages.WebPageBase.PopContext() +229
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +154
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651188
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Home Controller:
public class HomeController : BaseController
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Title="Portfolio";
return View(new ContactMessage());
}
[HttpPost]
public ActionResult Index(ContactMessage message)
{
if (ModelState.IsValid)
{
using (var db = new MessageDatabase())
{
message.DateSent = DateTime.Now;
db.ContactMessages.Add(message);
Success(string.Format("Message received! Thanks, I will try to get back to you as soon as possible."), true);
db.SaveChanges();
}
TempData["ContactMessage"] = message;
return RedirectToAction("Index");
}
Danger("Looks like something went wrong. Please check your form.");
ViewBag.Title = "Portfolio";
return View(message);
}
...
}
Account Controller:
public class AccountController : BaseController
{
//
// GET: /Account/
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Login()
{
var authModel = new Authentication();
return View(authModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Authentication authModel)
{
if (!ModelState.IsValid)
{
return View(authModel);
}
if (WebSecurity.Login(authModel.Username, authModel.Password))
{
return new RedirectResult("/");
}
else
{
ViewBag.ErrorMessage = "The username and/or password was incorrect";
return View(authModel);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Logout(Authentication authModel)
{
if (WebSecurity.Login(authModel.Username, authModel.Password))
{
WebSecurity.Logout();
Success("You have been logged off", true);
return new RedirectResult("/");
}
}
[HttpGet]
public ActionResult Register()
{
return View(new Registration());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Registration authModel)
{
if (ModelState.IsValid)
{
if (!WebSecurity.UserExists(authModel.Username))
{
WebSecurity.CreateUserAndAccount(authModel.Username, authModel.Password);
WebSecurity.Login(authModel.Username, authModel.Password, true);
return new RedirectResult("/");
}
ViewBag.ErrorMessage = string.Format("The user {0} already exists. Please try a different username.",
authModel.Username);
}
return View(authModel);
}
}
View that causes problems:
#model app.Models.Authentication
#{
ViewBag.Title = "Login";
}
<div class="container">
<h2>Login</h2>
<div class="form-horizontal">
#if (WebSecurity.IsAuthenticated)
{
<p>You are currently logged in.</p>
}
else
{
<hr />
<p>#ViewBag.ErrorMessage</p>
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-group 12u">
<p>
#Html.LabelFor(m => m.Username) #Html.ValidationMessageFor(m => m.Username)<br />
#Html.EditorFor(m => m.Username)
</p>
</div>
<div class="form-group 12u">
<p>
#Html.LabelFor(m => m.Password) #Html.ValidationMessageFor(m => m.Password)<br />
#Html.PasswordFor(m => m.Password)
</p>
</div>
<div class="form-group 12u">
<p>
<input type="submit" value="Login" />
</p>
</div>
<div class="form-group 12u">
<p>Don't have an account? #Html.ActionLink("Register", "Register")</p>
<p>#Html.RouteLink("Return Home", new { controller = "Home" })</p>
</div>
}
}
</div>
RoutesConfig file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
My best guess is that somewhere, probably in your layout, you're doing something like:
#Html.Partial("_Contact")
Intending to bring a contact form or something into maybe a sidebar area. When you call a partial, you implicitly pass the model of the current view, the same as if you were to do:
#Html.Partial("_Contact", Model)
If the partial doesn't utilize a model, then this won't necessarily cause problems. However, if your partial does define a model, then it must be passed an instance of that type. You could probably fix it by just doing something like:
#Html.Partial("_Contact", new ContactMessage())
However, with items like this in your layout, you should actually use child actions:
#Html.Action("Contact", "Home")
Then, you can define a Contact action in HomeController that returns your partial view and defines a model to be passed with it it. This takes the rendering of this block completely out of the context of the rest of the page, so you don't get conflicts from context bleed-over like you have here.
I think that you want return RedirectToAction("ActionName", "ControllerName") instead of return RedirectResult("Path").
RedirectToAction - https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction(v=vs.118).aspx#M:System.Web.Mvc.Controller.RedirectToAction%28System.String,System.String%29
RedirectResult - https://msdn.microsoft.com/en-us/library/system.web.mvc.redirectresult(v=vs.118).aspx

The controller for path '/Home' was not found or does not implement IController

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.

MVC3 Drop Down List [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
MVC3 Razor (Drop Down List)
I've been getting "Object reference not set to an instance of an object.". Been trying to figure out this error for the past 12 hours. Hope someone can help.
This is causing the error.
#Html.DropDownListFor(c => c.CategoryID, Model.CategoryTypeList)
In SearchController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Demo.Models;
namespace Demo.Controllers
{
public class SearchController : Controller
{
//
// GET: /Search/
public ActionResult DisplayCategory()
{
var model = new SearchModel();
model.CategoryTypeList = GetCategory();
return View(model);
}
private List<SelectListItem> GetCategory()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "1", Value = "1" });
items.Add(new SelectListItem { Text = "2", Value = "2" });
return items;
}
}
}
In SearchModel
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Demo.Controllers;
namespace Demo.Models
{
public class SearchModel
{
public List<SelectListItem> CategoryTypeList { get; set; }
[Display(Name = "Category")]
public string CategoryID { get; set; }
}
}
In CSHTML
#model Demo.Models.SearchModel
#{
ViewBag.Title = "Search";
}
<h2>Search</h2>
#using (Html.BeginForm())
{
<table>
<tr>
<td>#Html.LabelFor(c => c.CategoryID)</td>
<td>#Html.DropDownListFor(c => c.CategoryID, Model.CategoryTypeList)</td>
</tr>
</table>
}
Stack Trace
[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Home_Search_cshtml.Execute() in c:\Users\User_me\Documents\Visual Studio 2010\Projects\Demo\Demo\Views\Home\Search.cshtml:12
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +272
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +67
System.Web.WebPages.StartPage.RunPage() +58
System.Web.WebPages.StartPage.ExecutePageHierarchy() +94
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +172
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +574
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +360
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +409
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +60
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +391
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +285
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +232
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +68
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +61
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +31
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +56
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +110
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Per your comments above, if you want to call this as a seperate unit within another page, then you will need to either pass the model in using Html.RenderPartial, or call Html.RenderAction in order to execute the entire action and output the resulting HTML.
Using Html.RenderPartial
#*
Assuming that you have already initialized some variable
called 'mySearchModel'
*#
#Html.RenderPartial("DisplayCategory", mySearchModel)
This will ensure that the Model property on the view gets set.
Using Html.RenderAction
//Slight change to your action method to ensure it returns
// a partial view, and will only ever be called as a child
// action of another action.
[ChildActionOnly]
public ActionResult DisplayCategory()
{
var model = new SearchModel();
model.CategoryTypeList = GetCategory();
return PartialView(model);
}
#Html.RenderAction("DisplayCategory")
Further reading:
http://haacked.com/archive/2009/11/17/aspnetmvc2-render-action.aspx
http://devlicio.us/blogs/derik_whittaker/archive/2008/11/24/renderpartial-vs-renderaction.aspx

MVC2 Ajax Form Submission causes 'Cannot create an instance of an interface' error

I'm having problems submitting a form via AJAX to my controller. Other people with similar error message seem to have issues around using interfaces as types on their controller method stub, I don't have that issue. I've included my partial view and controller code, if I missed any information out just let me know. I suspect it has something to do with the creation of the model after I change the value in the drop down list, but the error message isn't the most helpful so I'm a bit stuck!
My Partial View:
<% using (Ajax.BeginForm("RequestDetails", "Home", new { RequestId = Model.Request.RequestId, RequestStatus = Model.Request.Status }, new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "Details"
},
new { #class = "jqtransform" }))
{%>
<%= Html.LabelFor(m => Model.Request.Name) %>
<p><%= Html.Encode(Model.Request.Name)%> </p>
<%= Html.LabelFor(m => Model.Request.Status) %>
<% if (Html.IsAdmin(this.Page))
{%>
<div class="rowElem">
<%=Html.DropDownListFor(m => Model.Request.Status, (IEnumerable<SelectListItem>)ViewData["requestStatus"], null, new { onchange = "this.form.submit();" })%>
</div>
<% }
else
{ %>
<p><%= Html.Encode(Model.Request.Status.GetStringValue())%> </p>
<% } }%>
My Controller:
[HttpPost]
public PartialViewResult RequestDetails(RequestDetailModel model, Guid RequestId, string RequestStatus)
{
if (ModelState.IsValid)
{
RequestMethods requestMethods = new RequestMethods();
IRequest request = _requestRepo.GetRequestById(CurrentUser, RequestId, CompanyId);
requestMethods.UpdateRequestStatus(request, CurrentUser, model.NewComment, model.Request.Status);
}
model.Request = _requestRepo.GetRequestById(CurrentUser, RequestId, CompanyId);
return PartialView(model);
}
The exact error thrown is:
Cannot create an instance of an interface.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) at System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) at System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) at System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) at System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
You haven't shown your RequestDetailModel object but if there are properties that are interface type the default model binder is not able to populate them. For example if you have the following:
public class RequestDetailModel
{
public IRequest Request { get; set; }
}
where IRequest is an interface or an abstract class this won't work. If you want to use interfaces in your models you will need to write a custom model binder. Here's one example of such custom model binder that works with abstract classes but interfaces would be the same.

how I can bind my datasource to view?

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.

Resources