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.
Related
Note as of 9/16/2019 at 3:30 EDT
I have disabled the parts of my app that use the SQL Server DB so my site would not crash. Just as info, in case anyone access my site and can't reproduce the error.
I have read most if not all of the similar threads to no avail. My site uses BOTH MySQL and SQLserver. Everything works fine on my PC [localhost]. I issued the code for the first time this weekend, and have run into this problem with the published code on my hosting site. I am able to access the MySQL DB just fine, but when I try and access the SQLServer, I get the error -- Keyword not supported: 'data source HOST.com;initial catalog'.
Web.config
<connectionStrings>
<add name='DefaultConnection' providerName='System.Data.SqlClient' connectionString='Data Source=[HOST Server];Initial Catalog=aspnet-Lat34North-20190423140228;Integrated Security=SSPI' />
<add name='Lat34NorthContext' providerName='System.Data.SqlClient' connectionString='Data Source=[HOST Server];Initial Catalog=Lat34North;Integrated Security=False;User Id=[user id 1]; Password=[password 1]' />
<!-- Production -->
<add name="CitiesContext" connectionString="Data Source=[HOST Server]; Database=Lat34CitiesSQL; uid=[user id 2]; pwd=[password 2];" providerName="MySql.Data.MySqlClient" />
DAL
using Lat34North.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace Lat34North.DAL
{
public class Lat34NorthContext : DbContext
{
public DbSet<Photo> Photo { get; set; }
public DbSet<MarkersPrevNext> MarkersPrevNext { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Photo>().Property(p => p.PhotoFile).HasColumnType("image");
modelBuilder.Entity<MarkersPrevNext>().HasKey(t => new { t.StateCounty, t.Sequence });
}
}
}
Controller
using System;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using System.Data.Entity.Spatial;
using Lat34North.DAL;
using Lat34North.Models;
namespace Lat34North.Controllers
{
public class HistoricMarkersALController : BaseController
{
private ALMarkersContext db = new ALMarkersContext();
private Lat34NorthContext db2 = new Lat34NorthContext();
---- skip ahead --
int CurrentCount = CountPrevNext(PrevNextLocation, "M"); // Count number if records created today
if (CurrentCount == 0)
{
var temps = db.ALHistoricMarkers.Where(t => t.County == county_name).OrderBy(t => t.Title).ToList();
string dateCreated = DateTime.Now.ToString("yyyy-MM-dd");
int i = 0;
foreach (var temp in temps)
{
db2.MarkersPrevNext.Add(new MarkersPrevNext() ***<--Error here***
{
StateCounty = PrevNextLocation,
Sequence = i,
Type = "M", // Type M - marker
MarkerKey = temp.MarkerKey,
CraetedDate = dateCreated
});
i++;
}
db2.SaveChanges();
}
return View(vModel);
}
Error
Server Error in '/' Application.
________________________________________
Keyword not supported: 'data source HOST.com;initial catalog'.
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: Keyword not supported: 'data source HOST.com;initial catalog'.
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: Keyword not supported: 'data source {Server name.com];initial catalog'.]
System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) +418
System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) +99
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +59
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +25
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +166
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +57
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +148
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.<SetConnectionString>b__18(DbConnection t, DbConnectionPropertyInterceptionContext`1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.SetConnectionString(DbConnection connection, DbConnectionPropertyInterceptionContext`1 interceptionContext) +360
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +270
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +129
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.get_ProviderName() +11
System.Data.Entity.Internal.DefaultModelCacheKeyFactory.Create(DbContext context) +92
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +515
System.Data.Entity.Internal.InternalContext.Initialize() +20
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +38
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +83
Lat34North.Controllers.BaseController.DeletePrevNext(String PrevNextLocation, String type) in c:\Lat34North\Lat34North\Controllers\CommonController.cs:71
Lat34North.Controllers.HistoricMarkersALController.SearchChurches(String option, String search) in c:\Lat34North\Lat34North\Controllers\HistoricMarkersALController.cs:459
lambda_method(Closure , ControllerBase , Object[] ) +147
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(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.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
change your config to the following. you missed a closing ' for connectionString=''
<add name='Lat34NorthContext' connectionString='Data Source=[HOST Server];Initial Catalog=Lat34North;Integrated Security=False;User Id=[user id 1]; Password=[password 1];Min Pool Size=20; Max Pool Size=200;' providerName="System.Data.SqlClient" />
If your SQL Server is on one domain controller and you are trying to connect to it from another domain controller then you will get this error when IntegratedSecurity = true;
Integrated security means simply - use your windows credentials for login verification to SQL Server. So, if you are logged in to a different domain controller then it will fail. In the case where you are on two different domain controllers then you have no choice but to use IntegratedSecurity = false;
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
Call me crazy but I'm developing an ASP.NET MVC4 site in F#. Here's my first roadblock; in the controller I submit a dictionary, this way:
[<HandleError>]
type FooController() =
inherit Controller()
member this.Index () =
this.ViewData.Add("Foo", "Bar")
this.ViewData.Add("Baz", dict [ (0, 0); (1, 3); (2, 2); ] )
this.View() :> ActionResult
Now I want to iterate through the values in the Razor template, how to do it? I've tried this:
#foreach (var time in #ViewBag.Baz.Keys)
{
<hr /><p>Time is #time, and value is #ViewBag.Baz[time]</p>
}
But it throws this error:
Line 119: Total: <span class="highlight">6449</span> kW/h.
Line 120: </p>
Line 121: #foreach (var time in (#ViewBag.Baz).Keys)
Line 122: {
Line 123: <hr /><p>Time is #time, and value is #ViewBag.Baz[time]</p>
[RuntimeBinderException: 'object' does not contain a definition for 'Keys']
CallSite.Target(Closure , CallSite , Object ) +280
System.Dynamic.UpdateDelegates.UpdateAndExecute1(CallSite site, T0 arg0) +924
ASP._Page_Views_lobby_Index_cshtml.Execute() in c:\Users\knocte\documents\visual studio 2012\projects\fsolar\conclavesolarweb\conclavesolarwebwebapi\Views\Lobby\Index.cshtml:121
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
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +378
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +33
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +853420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +265
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +837892
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
So the problem you are experiencing is a know limitation of the dynamic keyword and explicit interface implementations. Unfortunately Map will have this problem too. If you really want to use a ViewBag like this, you could use an actual Dictionary<int,int>.
Ultimately, however you should play to F#'s strengths, which is static typing and low ceremony type creation. Create lightweight types in your F# code and use the #model keyword in your views.
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);
}
I have an MVC 4 project using EF 5 Code First. I am trying to install MiniProfile at no avail.
I pulled MiniProfiler 2.0.1 and MiniProfiler.EF 2.0.2 from NuGet, added the following on the Global.asax.cs:
protected void Application_Start()
{
MiniProfilerEF.Initialize();
}
Immediately upon run, I get this error:
The provider did not return a DbSpatialServices instance.
Line 58: if (user != null)
Line 59: {
Line 60:>>> if (user.Places != null)
Line 61: {
Line 62: var place= user.Places .OrderByDescending(x => x.CreationTime).FirstOrDefault();
[ProviderIncompatibleException: The provider did not return a DbSpatialServices instance.]
System.Data.Common.DbProviderServices.GetDbSpatialDataReader(DbDataReader fromReader, String manifestToken) +62
System.Data.Common.DbProviderServices.GetSpatialDataReader(DbDataReader fromReader, String manifestToken) +101
System.Data.Spatial.SpatialHelpers.CreateSpatialDataReader(MetadataWorkspace workspace, DbDataReader reader) +70
System.Data.Common.Internal.Materialization.Shaper.CreateSpatialDataReader() +12
System.Data.Common.Utils.Singleton`1.get_Value() +25
System.Data.Common.Internal.Materialization.Shaper.<GetSpatialPropertyValueWithErrorHandling>b__d(DbDataReader reader, Int32 column) +12
System.Data.Common.Internal.Materialization.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) +149
System.Data.Common.Internal.Materialization.Shaper.GetSpatialPropertyValueWithErrorHandling(Int32 ordinal, String propertyName, String typeName, PrimitiveTypeKind spatialTypeKind) +269
lambda_method(Closure , Shaper ) +942
System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly(Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) +239
lambda_method(Closure , Shaper ) +221
System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) +163
System.Data.Common.Internal.Materialization.SimpleEnumerator.MoveNext() +88
System.Data.Objects.DataClasses.RelatedEnd.Merge(IEnumerable`1 collection, MergeOption mergeOption, Boolean setIsLoaded) +222
System.Data.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption) +218
System.Data.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption) +25
System.Data.Objects.DataClasses.RelatedEnd.Load() +37
System.Data.Objects.DataClasses.RelatedEnd.DeferredLoad() +300
System.Data.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +85
System.Data.Objects.Internal.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item) +105
System.Data.Entity.DynamicProxies.User_C006B0EF9498157C70250EEE038C6BEADB719A2D5BDC4AA1FB567FB579AECEB5.get_Places() +55
Project.Web.Controllers.PlaceController.Ribbon() in c:\Project\Project.Web\Controllers\PlaceController.cs:60
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +204
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +30
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +58
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +225
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +42
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +54
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +9
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__4(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +47
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +59
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +22
System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +10
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +64
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +71
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1121
I have a couple of DbGeography types in my Places POCO.
public class Places
{
public Guid PlacesId { get; set; }
...
public DbGeography Location { get; set; }
public DbGeography Area { get; set; }
...
}
I have tried searching for that error but it does not show up in google anywhere.
This looks like a bug in MiniProfiler, it should be reported at: http://community.miniprofiler.com
In particular profiling EF is very tricky, a lot of the work is done by wrapping every "provider" it uses. It seems that EFProfiledDbProviderFactory needs some special logic to locate, intercept and wrap the spatial services.