MVC3 Drop Down List [duplicate] - asp.net-mvc

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

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

"Sequence contains no elements" when using .Any()

This seems like a straightforward question. I am beginning to suspect a bug in razor.
if (Model.athleteImages .Any()){
//some code
}
I have replaced the above with the following:
if (Model.athleteImages.Count > 0)
{
var i = 0;
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
while (i + 1 < Model.athleteImages.Count())
{
i++;
<li data-target="#carousel-example-generic" data-slide-to="#i"></li>
}
}
This always throws "Sequence contains no elements" for collections with no elements e.g. Count() = 0.
Any() is supposed to test if a Sequence contains elements. That is its entire purpose.
I have also tried
if (Model.athleteImages.FirstOrDefault().[fieldName] != null){
//some code
}
Same result.
here is some relevant code from the controller for those wondering what the Images collection is
var adImages = from i in db.athleteImages
where thisAd.albumId == i.albumId
where i.deleted == false
select i;
viewModel.athleteImages = athleteImages.ToList();
Here is the View Model Class
public class ListingViewModel
{
public site site { get; set; }
public userAd userAd { get; set; }
public List<athleteImage> athleteImages { get; set; }
public string categoryName { get; set; }
public int categoryId { get; set; }
public string subcategoryName { get; set; }
public int subcategoryId { get; set; }
}
Stack Trace
[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.First(IEnumerable`1 source) +269
ASP._Page_Views_userAds_Listing_cshtml.Execute() in c:\Users\Bill\Documents\Visual Studio 2013\Projects\CuriousMarketplaces\CuriousMarketplaces\Views\userAds\Listing.cshtml:32
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +105
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651116
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
If what you really care about is whether or not there are any images in the collection, something like this might make more sense:
if (Model.Images.Count > 0) {
}
Any() will throw an exception if the source is null, this is documented behavior and how it is supposed to work: http://msdn.microsoft.com/en-us/library/vstudio/bb534972%28v=vs.100%29.aspx
Dave's solution is pretty good but I would add a null check, Count will also throw an exception if the object is null.
if(Model.Images != null && Model.Images.Count > 0) {
}
Dan gave me the hint I needed.
Even though the debugger was indicating that the error was occurring at the closing block of my if block, that was not the case.
In a later block of code in the same view, I have this:
<div class="item active" id="0">
<div style="width:400px;height:300px;text-align:center;background-color:black;">
<img src="/Content/Images/Deals/1/#Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
<div class="carousel-caption">
some caption
</div>
</div>
</div>
To fix the problem, I need to test again. so:
if (Model.athleteImages.Count > 0)
{
<div class="item active" id="0">
<div style="width:400px;height:300px;text-align:center;background-color:black;">
<img src="/Content/Images/Deals/1/#Model.athleteImages.First().fullImage" style="height:300px;" alt="...">
<div class="carousel-caption">
some caption
</div>
</div>
</div>
}
What fries my brain is that the error message indicated a problem at line 32. In reality it was on line 37.

WebGrid.GetHtml() throws Object reference not set to an instance of an object when the

Description
I can not get the WebGrid sort to work. It keeps throwing NullReferenceException when the view tries to load.
Environment
WebGrid 2.0.0.0, VisualStudio 2012, MVC version 4.0
Details
My controller action does not attempt to do any sorting yet. I tried to simulate the sort by clicking on a column header, the controller's index action executes without any errors. When the view tries to load I get a runtime error NullReferenceException was unhandled by user code
In debug mode I can trace the error back to some code in the WebGrid's GetHtml call that attempts to reference the Rows object 'grid2.Rows' threw an exception of type 'System.NullReferenceException'
I am using a strongly typed collection to fake up some data in the controller, add it to the model and serve the model to the view.
I have tried a number of different variations, but here is the current state of my code:
The controller action
public class HomeController : Controller
{
public ActionResult Index(string sort, string sortdir)
{
LandingPageData myData = new LandingPageData();
myData.UserName = "JoeBagodonuts";
ReplacementReserveMvcDesign.ViewModels.ProjectCounts<ProjectCount> currentWork = new ProjectCounts<ProjectCount>();
//Hacking up some data
for (int i = 0; i < 1000; i++)
{
ProjectCount currentCount = new ProjectCount();
currentCount.ProjectId = "PA-" + i.ToString();
currentCount.DevelopmentName = "Development Name " + i.ToString();
currentCount.OpenCount = i;
currentCount.ActionRequiredCount = i;
currentWork.Add(currentCount);
}
myData.UserProjectCounts = currentWork;
return View(myData.UserProjectCounts);
}
The View
#model IEnumerable<ProjectCount>
#using System.Web.Helpers
#using ReplacementReserveMvcDesign.ViewModels
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
WebGrid grid2 = new WebGrid(Model, canSort:true);
}
#grid2.GetHtml(
columns: grid2.Columns(
grid2.Column(columnName:"ProjectId",
header: "Project ID"),
grid2.Column(columnName:"DevelopmentName",
header:"Development Name"),
grid2.Column(columnName:"OpenCount",
style: "text-align-center",
header: "Open Requests"),
grid2.Column(columnName:"ActionRequiredCount",
header: "Action Required",
style: "text-align-center")
))
Here is the stack trace:
[NullReferenceException: Object reference not set to an instance of an object.]
lambda_method(Closure , ProjectCount ) +81
System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count) +147
System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count) +37
System.Linq.<GetEnumerator>d__0.MoveNext() +330
System.Linq.<SkipIterator>d__4d`1.MoveNext() +397
System.Linq.<TakeIterator>d__3a`1.MoveNext() +375
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +535
System.Linq.Enumerable.ToList(IEnumerable`1 source) +79
System.Web.Helpers.WebGridDataSource.GetRows(SortInfo sortInfo, Int32 pageIndex) +166
System.Web.Helpers.WebGrid.get_Rows() +118
System.Web.Helpers.<>c__DisplayClass4.<Table>b__3(TextWriter __razor_helper_writer) +1191
System.Web.WebPages.HelperResult.ToString() +102
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, Object content) +16
ASP._Page_Views_Home_Index_cshtml.Execute() in c:\Users\is_rbm\documents\visual studio 2012 \projects\replacementreservemvcdesign\replacementreservemvcdesign\Views\Home\Index.cshtml:14
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +279
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +125
System.Web.WebPages.StartPage.ExecutePageHierarchy() +142
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +180
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +377
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +32
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +854204
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +838676
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
I am eager to use MVC in this project, but I have to be able to build searchable,sortable and pageable grids quickly and easily.
I changed the controller's index method to return a List of ProjectCount objects rather than a strongly typed collection and everything work now.
Here's the new code for the controller index method.
public ActionResult Index(string sort, string sortdir)
{
List<ProjectCount> items = new List<ProjectCount>();
for (int i = 0; i < 1000000; i++)
{
ProjectCount currentCount = new ProjectCount();
currentCount.ProjectId = "PA-" + i.ToString();
currentCount.DevelopmentName = "Development Name " + i.ToString();
currentCount.OpenCount = i;
currentCount.ActionRequiredCount = i;
items.Add(currentCount);
}
return View(items);
}

Calling action method in MVC with $.post and then returning an object for Edit not working

I'm trying to call an action method in an MVC4 application using jQuery. I'm using a button on Edit form shown in fancybox:
<input type="button" value="Approve" id="Approve" />
I'm using a jquery $.post on this button click
$("#Approve").click(function () {
debugger;
var ID = $("#AjaxGrid tbody tr:first").attr("data-pkey");
debugger;
var postParams = { Id: ID }
$.post('#Html.Raw(Url.Action("Approve"))', postParams)
.fail(function () {
alert("error occured while Approving");
});
});
In the controller the following is my action method:
[HttpPost]
public ActionResult Approve(long id)
{
Evaluation evaluation = db.EvaluationRepository.GetByID(id);
evaluation.EvaluationStatusID = Convert.ToInt32(EvaluationStatusType.Approved);
return PartialView(evaluation);
}
But I always get the same result i.e. error occured while Approving
Can any one help me in finding what's wrong?
got this error with F12 on browser
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and this annoying detail
Server Error in '/' Application.
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Approve(Int64)' in 'CubicHRMWeb.Areas.Employees.Controllers.EvaluationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
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.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Approve(Int64)' in 'CubicHRMWeb.Areas.Employees.Controllers.EvaluationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
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:
[ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Approve(Int64)' in 'CubicHRMWeb.Areas.Employees.Controllers.EvaluationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters]
System.Web.Mvc.ActionDescriptor.ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary2 parameters, MethodInfo methodInfo) +654635
System.Web.Mvc.<>c__DisplayClass1.<Execute>b__0(ParameterInfo parameterInfo) +18
System.Linq.WhereSelectArrayIterator2.MoveNext() +85
System.Linq.Buffer1..ctor(IEnumerable1 source) +217
System.Linq.Enumerable.ToArray(IEnumerable1 source) +78
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +133
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass81.b__7(IAsyncResult ) +12
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +237
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +12
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c_DisplayClass2a.b_20() +24
System.Web.Mvc.Async.<>c_DisplayClass25.b_22(IAsyncResult asyncResult) +126
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +61
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +49
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +49
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225
HTML:
<input type="button" value="Approve" id="Approve" data-action="#Url.Action("Approve")" />
JS:
Number.tryParseInt = function(value) {
return value.toString().match(/^(\d)/) != null;
}
Number.tryParseFloat = function(value) {
return value.toString().match(/^(\d|\d\.|\.\d)/) != null;
}
$("#Approve").click(function () {
var
id = $("#AjaxGrid tbody tr:first").data('pkey'),
postParams = { id: 0 };
if (!Number.tryParseFloat(id)) {
alert('id "' + id + '" is not a number');
return false;
}
postParams.id = parseInt(id);
$.post($(this).data('action'), postParams)
.done(function(data) {
alert('ok Approving: ' + data.EvaluationStatusID);
})
.fail(function () {
alert('error occured while Approving');
});
return false;
});
C#:
Why you are using ActionResult if not using the return?
[HttpPost]
public JsonResult Approve(long id)
{
Evaluation evaluation = db.EvaluationRepository.GetByID(id);
evaluation.EvaluationStatusID = Convert.ToInt32(EvaluationStatusType.Approved);
return Json(evaluation);
}
Need you a larger number of '2.147.483.647'?, if you continue with the error, try using int:
[HttpPost]
public JsonResult Approve(int id)
{
Evaluation evaluation = db.EvaluationRepository.GetByID(id);
evaluation.EvaluationStatusID = Convert.ToInt32(EvaluationStatusType.Approved);
return Json(evaluation);
}
From your stack trace it appears the id parameter of your AJAX call is null, data-pkey is empty for the selected element.
Without seeing your HTML I can't tell you why this is but you need to look at and change the $("#AjaxGrid tbody tr:first") selector.
I think there is a Circular Refrence Issue
My Model Class
public class Evaluation
{
[Key]
public int ID {get; set;}
public int UserID {get; set;} //whose evaluation is due
public DateTime EvaluationDueOn {get; set;}
public DateTime EvaluatedOn {get; set;}
public decimal evaluationAmount {get; set;}
public string comments {get; set;}
public string ApproverID {get; set;} //(userid of staff doing approval)
public int EvaluationStatusID { get; set; }
public virtual Users EvaluatedUser { get; set; }
public virtual Users ApprovingUser { get; set; }
}
uses Navigational properties like
public virtual Users EvaluatedUser { get; set;
public virtual Users ApprovingUser { get; set; }
and Serialization problem occurs due to this Circular Refrence

The model item passed into the dictionary is of type 'System.Collections.Generic.List error

I get the following error when trying to run my application:
'The model item passed into the dictionary is of type 'System.Collections.Generic.List1[MvcApplication2.Models.Blog]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[MvcApplication2.Models.BlogDataEntities]'.
'
Here is the stack trace:
[InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[MvcApplication2.Models.Blog]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MvcApplication2.Models.BlogDataEntities]'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +324899
System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +377
System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +48
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +99
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.<InvokeActionResultWithFilters>b__19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
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() +8969117
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
And here is my BlogController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
namespace MvcApplication2.Controllers
{
public class BlogController : Controller
{
//
// GET: /Blog/
public ActionResult Index()
{
using (var db = new BlogDataEntities())
{
return View(db.Blogs.ToList());
}
}
//
// GET: /Blog/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Blog/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Blog/Create
[HttpPost]
public ActionResult Create(Blog blog)
{
try
{
using (var db = new BlogDataEntities())
{
db.Blogs.Add(blog);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Blog/Edit/5
public ActionResult Edit(int id)
{
using (var db = new BlogDataEntities())
{
return View(db.Blogs.Find(id));
}
}
//
// POST: /Blog/Edit/5
[HttpPost]
public ActionResult Edit(int id, Blog blog)
{
try
{
using (var db = new BlogDataEntities())
{
db.Entry(blog).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch
{
return View();
}
}
//
// GET: /Blog/Delete/5
public ActionResult Delete(int id)
{
using (var db = new BlogDataEntities())
{
return View(db.Blogs.Find(id));
}
}
[HttpPost]
public ActionResult Delete(int id, Blog blog)
{
try
{
using (var db = new BlogDataEntities())
{
db.Entry(blog).State = System.Data.EntityState.Deleted;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
The problem is that you have a controller action which passes a List<Blog> instance to a view which is strongly typed to IEnumerable<BlogDataEntities> which is not possible.
So you have a controller action like this:
public ActionResult Foo()
{
List<Blog> blogs = ...
return View(blogs);
}
and the corresponding view:
#model IEnumerable<BlogDataEntities>
...
Another possibility for this error occurring is that your view is typed to the correct model that the controller action passed but inside this view you tried to render a partial which is typed to a different model:
#model List<Blog>
...
#Html.Partial("_MyPartial")
where _MyPartial.cshtml looks like this:
#model IEnumerable<BlogDataEntities>
...
which once again is not possible. In this case you could use the second argument to the Html.Partial helper to provide a correct model for this partial.

Resources