how I can bind my datasource to view? - asp.net-mvc

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.

Related

No parameterless constructor defined for this object for MVC Controller

I have this controller as you can see :
namespace Web.Front.Controllers
{
public class CarController : Controller
{
ICarService _CarService;
public CarController(ICarService carService)
{
_CarService = carService;
}
// GET: Car
public ActionResult Index()
{
return View();
}
}
}
When i call index action i get this error :
No parameterless constructor defined for this object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +119
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.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'Web.Front.Controllers.CarController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +102
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +184
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
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.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
As a note i am using ninject to inject services to controllers .when i remove the service from constructor it works .
The ninject code:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<DidbaanContext>().To<DidbaanContext>();
kernel.Bind<ICarService>().To<CarService>();
kernel.Bind<ICarRepository>().To<CarRepository>();
}
mvc needs parameterless contructions.
If you have no constructor, .Net-runtime create parameterless contruction automaticly, otherwise if you have a contruction with parameter, than the runtime don't do that and raise an error.
Ether you create a new carService on each controler, or you use a serviceProvider.
The unittest are simple with a serviceprovider.
With asp.net core its easy enter link description here, if you use mvc 4 or 5. you can see here a see here a sample enter link description here

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

Where is this System.MissingMethodException occurring? How can I tell?

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;

MVC Model issue can you diagnose what this is saying?

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...

Resources