Html.Serialize return NullReferenceException - asp.net-mvc

I have an ViewModel like
namespace ViewModel
{
[Serializable]
public class TestViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
Also, I have one action method:
public ActionResult Index()
{
TestViewModel model = new TestViewModel
{
Id = -1,
Name = "Some name",
Description = "Some description"
};
return View(model);
}
And my View something like this:
#using Microsoft.Web.Mvc
#model ViewModel.TestViewModel
#using (Html.BeginForm())
{
Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned);
//....Editor fields
}
In line "Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned);" debugger is stopped and returns exception "object reference not set to an instance of an object" (NullReferenceException). Although, the Model is not null and contains initial values.
I use ASP.Net MVC 3(Razor) and stack trace is below:
in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper,
String name, Object data, SerializationMode mode, Boolean useViewData, MvcSerializer
serializer)
in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper,
String name, Object data, SerializationMode mode, Boolean useViewData)
in Microsoft.Web.Mvc.SerializationExtensions.Serialize(HtmlHelper htmlHelper, String
name, Object data, SerializationMode mode)
in ASP._Page_Views_Wizard_Index_cshtml.Execute()
in c:\Projects\TestProject\Views\Wizard\Index.cshtml:line 15
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
in System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
in System.Web.WebPages.StartPage.RunPage()
in System.Web.WebPages.StartPage.ExecutePageHierarchy()
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,
TextWriter writer, WebPageRenderingBase startPage)
in System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer,
Object instance)
in System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter
writer)
in System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult)
in System.Web.Mvc.ControllerActionInvoker.
<>c__DisplayClass1c.InvokeActionResultWithFilters>b__19()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter,
ResultExecutingContext preContext, Func`1 continuation)
What's wrong in my code?

You need to use
#Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned)
if you want hidden field with model on form.

The problem was that I had assembly reference to Mvc2Futures ("Microsoft.Web.Mvc.dll"). But when I changed the reference to Mvc3Futures ("Microsoft.Web.Mvc.dll") all work fine.
Thanks a lot.

Related

#Html.EnumDropDownListFor() Additional information: Return type 'System.Int32' is not supported

#Html.EnumDropDownListFor() is throwing an error
An exception of type 'System.ArgumentException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: Return type 'System.Int32' is not supported."
Code from view
<div class="form-group">
<div class="col-md-10">
#Html.Label("Importance Level")
#Html.EnumDropDownListFor(model => model.NoticeCategory)
<span class="help-block">...</span>
</div>
</div>
Code from enum class
namespace OfficiumWebApp.Models.Enums
{
public enum NoticeCategories : byte
{
[Display(Name= "High")]
Hige = 1,
[Display(Name = "Medium")]
Medium = 2,
[Display(Name = "Low")]
Low = 3
}
I want the display names in the dropdown list so I'm not sure wht it's trying to return System.int32.
Any ideas where the problem could lie?
Thanks
EDIT: Forgot to include my view model code
[Display(Name = "Notice Category")]
public NoticeCategories? NoticeCategory { get; set; }
EDIT 2: Stack trace
at System.Web.Mvc.Html.SelectExtensions.EnumDropDownListFor[TModel,TEnum](HtmlHelper`1 htmlHelper, Expression`1 expression, String optionLabel, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.SelectExtensions.EnumDropDownListFor[TModel,TEnum](HtmlHelper`1 htmlHelper, Expression`1 expression, String optionLabel)
at System.Web.Mvc.Html.SelectExtensions.EnumDropDownListFor[TModel,TEnum](HtmlHelper`1 htmlHelper, Expression`1 expression)
at ASP._Page_Views_NoticeBoard_Create_cshtml.Execute() in .......................................................
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
enum returns as a string listing. I guess you previously replaced the return with an enum where an int value is returned. Drop your table and re-create your database table with migration without enum. The problem will be eliminated. it coused your previous model.
OR
Add a call to ToString on the returned property to the expression.
I had NoticeCategory defined as int in my notice class. I changeed this to IEnumerable

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.

Entity Framework doesn't create Database

i'm creating a database with entity framework, in an mvc asp.net application, using code first.
I'm new to the argument so be patient... I've created the database for the first time and all seems to be right; but couse of i didn't create a DropCreateDatabaseIfModelChanges method to change the tables i decided to manually delete the database.
The problem is that the database is not recreating!
I've implemented the initializer and it is in a different class from the context...
public class WidgetDbInitializer : DropCreateDatabaseIfModelChanges<WidgetDbContext>
{
}
Setted it up in Global.asax.cs and forced to init that
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<Portale.Models.WidgetDbContext>(new Portale.Models.WidgetDbInitializer());
var _initer = new WidgetDbInitializer();
using (var db = new WidgetDbContext())
{
_initer.Seedit(db);
db.Database.Initialize(true);
}
}
I've just the default connection string couse now i don't care about it...
Please help me i've read tons of articles over the web and i can't get a solution...
The error i get:
System.ArgumentNullException non è stata gestita dal codice utente
Message=Il valore non può essere null.
Nome parametro: key
Source=mscorlib
ParamName=key
StackTrace:
in System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
in System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.SortedEntityTypeIndex.Add(EdmEntitySet entitySet, EdmEntityType entityType)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Analyze()
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Configure()
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
in System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
in System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
in System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
in System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
in System.Data.Entity.Internal.InternalContext.Initialize()
in System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
in System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
in System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
in System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
in System.Linq.Queryable.Join[TOuter,TInner,TKey,TResult](IQueryable`1 outer, IEnumerable`1 inner, Expression`1 outerKeySelector, Expression`1 innerKeySelector, Expression`1 resultSelector)
in Portale.Controllers.WidgetContainerController.Index() in C:\Users\doompro\Documents\Visual Studio 2010\Projects\Portale\Portale\Controllers\WidgetContainerController.cs:riga 56
in lambda_method(Closure , ControllerBase , Object[] )
in System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
in System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
override Seed function in your WidgetDbInitializer class and try to add some data to your database .
protected override void Seed(WidgetDbContext context)
{
context.yourodel.add(new class() )
}
first check your overriden seed invoke correctly , then if your database dose not generated you will get an exception .
Solved the problem:
public class Widget
{
//This properties rapresent the primary key for entity framework
[Key]
public int WidgetID { get; set; }
//Foreing key to the column where this widget is stored
public virtual int ColumnID { get; set; }
//The title of the widget
public string Title { get; set; }
//Controller of the Widget, this property may be used on the RenderAction call
public string Controller { get; set; }
//ActionMethod of the Widget, this property may be used on the RenderAction call
public string ActionMethod { get; set; }
//The Type of the Model, used on deserialization
public Type ModelType { get; set; }
//The context of the widget
public string SerializedModel { get; set; }
}
The database just didn't accept the type "Type", all working fine as soon as I deleted that field... I just didn't look at it because it was working with the "Object" type, didn't expect it doesnt with Type..

List <string> to display in Partial MVC 3-Razor View -AJAX call

I know this would be easy for most of you folks, but I am new to this .net stuff.
Trying to pass a list of string List to partial view, which is called with jquery load method
$('#tree-res').load("#Url.Action("GetTreeView" , "TreeView" )");
and i am calling this view from controller
public PartialViewResult GetTreeView()
{
List<string> list=new List<string>();
list.Add("Something");
return PartialView("TreeView",list);
}
Now, how to iterate over this list and display it in TreeView.cshtml
following throws errors :
#model List<string>
#foreach (var item in Model)
{
}
Thanks
Following is stack trace:
Line 1: #model List<string>
Line 2: #foreach (var item in Model)
Line 3: {
Line 4: }
Source File: c:\scm\branches\Quest\Views\TreeView\TreeView.cshtml
Line: 2
Stack Trace:
[NullReferenceException: Object reference not set to an instance
of an object.]
ASP._Page_Views_treeview_TreeView_cshtml.Execute() in
c:\scm\branches\Quest\Views \TreeView\TreeView.cshtml:2
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +88
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext,
TextWriter writer, Object instance) +220
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext
viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext
context) +303
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c_DisplayClass1c.b_19()
+23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func`1 continuation) +260
....
Certainly looks like your Model is null. Have you made sure you've recompiled since adding code in GetTreeView?

MVC 3: HtmlHelper.TextBoxFor(Expression<Func<MyModel,double?>>) Failing

Ok, so we've been converting an old project to .NET 4 and MVC 3, and it is mostly finished. I am now, however, receiving an error on a partial view when calling HtmlHelper.TextBoxFor(Expression<Func<MyModel,double?>>). HtmlHelper.TextBoxFor(Expression<Func<MyModel,string>>) works just fine, however.
Here are the relevant code snippets:
A model class:
public class MyClass
{
public string SomeString { get; set; }
public double? SomeNullableDouble { get; set; }
}
In the main view ViewModel:
public class MyMainViewModel
{
public MyClass A { get; set; }
public MyClass B { get; set; }
}
In the Partial View ViewModel:
public class MyPartialViewModel
{
public Expression<Func<MyMainViewModel, string>> SomeStringProperty { get; set; }
public Expression<Func<MyMainViewModel, double?>> SomeNullableDoubleProperty { get; set; }
public MyPartialViewModel(Expression<Func<AnalyzeCostViewModel, string>> someStringProperty, Expression<Func<AnalyzeCostViewModel, double?>> someNullableDoubleProperty)
{
SomeStringProperty = someStringProperty;
SomeNullableDoubleProperty = someNullableDoubleProperty;
}
}
In the Main View (We haven't bothered converting to Razor views just yet...):
<div>
<% Html.RenderPartial("MyPartialView", new MyPartialViewModel(m => m.A.SomeString, m => m.A.SomeNullableDouble)) %>
</div>
<div>
<% Html.RenderPartial("MyPartialView", new MyPartialViewModel(m => m.B.SomeString, m => m.B.SomeNullableDouble)) %>
</div>
In the Partial View (MyPartialView.ascx):
<p>
<%=Model.Helper.LabelFor(Model.SomeStringProperty, "SomeLabel:") %>
<%=Model.Helper.TextBoxFor(Model.SomeStringProperty)%>
<%=Model.Helper.TextBoxFor(Model.SomeNullableDoubleProperty , new { #class = "some-class" })%>
</p>
When trying to access the main view, I'm getting a compiler error:
Server Error in '\' Application.
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
[InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.]
System.Web.Mvc.ModelMetadata.FromLambdaExpression(Expression1 expression, ViewDataDictionary1 viewData) +522
System.Web.Mvc.Html.InputExtensions.TextBoxFor(HtmlHelper1 htmlHelper, Expression1 expression, IDictionary2 htmlAttributes) +59
System.Web.Mvc.Html.InputExtensions.TextBoxFor(HtmlHelper1 htmlHelper, Expression`1 expression) +50
ASP.views_(proprietary)._Render_control1(HtmlTextWriter __w, Control parameterContainer) in d:(proprietary)MyPartialView.ascx:37
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +109
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Page.Render(HtmlTextWriter writer) +29
System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +43
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060
The error occurs in the partial view for the nullable double property expression, but not the string one.
Is there an easy fix for this? Or is this something that will take some time to redesign?
As from this question, it may be necessary to set up an editor template for double?...
New file - Views/Shared/EditorTemplates/NullableDouble.aspx
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Double?>" %>
<%=Html.TextBox("", (Model.HasValue ? Model.Value : string.Empty), ViewData) %>
And then access this template from the view by using EditorFor:
<%=Html.EditorFor(model => model.SomeNullableDoubleProperty, new { #class = "some-class" }) %>
You have to use the Value property of your nullable type, as in:
Model.SomeNullableDoubleProperty.Value
See this answer for a detailed explanation.

Resources