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.
Related
For a client of ours we have an MVC action which returns PDF files. The following code is the logic to return the FileResult.
public FileResult DownloadAbsFile(string id)
{
String path = GetPathNameByID(id);
if (System.IO.File.Exists(path))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
string fileName = System.IO.Path.GetFileName(path);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
}
else
{
return null;
}
}
When I request a PDF file using the right URL most of the time there is no problem. However certain users get an error. The error is puzzling me for quite some time. The error I get is as follows.
Exception type: NullReferenceException
Exception message: Object reference not set to an instance of an object
at ASP._Page_Views_Shared_SiteLayout_cshtml.Execute() in
xxx\Views\Shared\SiteLayout.cshtml:line xxx
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.WebPages.WebPageBase.<>c__DisplayClass3.
<RenderPageCore>b__2(TextWriter writer)
at System.Web.WebPages.HelperResult.WriteTo(TextWriter writer)
at System.Web.WebPages.WebPageBase.Write(HelperResult result)
at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName,
Action`1 body)
at System.Web.WebPages.WebPageBase.PopContext()
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.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.
<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at
On the specific line in the cshtml it tries to access the PageTitle in the ViewBag, which wasn't set. This value is never set, so I get this. But what I do not get is why it is trying to render the view in the first place.
Can anybody help me with this?
#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
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
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.
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?