Menu
  • HOME
  • TAGS

MvcSiteMapProvider “Home” button in menu not working onclick

Tag: asp.net-mvc-5,asp.net-mvc-routing,mvcsitemapprovider

I have a menu generated with MvcSiteMapProvider using a helper for bootstrap and routing:

Controller Home:

[MvcSiteMapNode(Title = "Home", Key = "home")]
public ActionResult Index()
{
    return View(model);
}

Controller Other:

[Route("mypageview", Name = "mypage")]
[MvcSiteMapNode(Title = "My Page", ParentKey = "home", Key = "mypage")]
public ActionResult mypage()
{
    mymodel model = .....
    return View(model);
}

Helper:

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        @foreach (var node in Model.Nodes)
            {
                if (node.Children.Any())
                {
                    <li>
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">@node.Title<strong class="caret"></strong></a>
                         <ul class="dropdown-menu">
                             @for (int i = 0; i < node.Children.Count; i++)
                             {
                                   <li>@Html.DisplayFor(x => node.Children[i])</li>
                             }
                         </ul>
                     </li>
                }
                else
                {
                    <li>
                         <a href="@node.Url" class="dropdown-toggle" data-toggle="dropdown">@node.Title</a>
                    </li>
                }
            }
     </ul>
</div> 

Layout View:

@Html.MvcSiteMap().Menu("BootstrapMenuHelperModel")

All of the menu items work perfectly and the dropdown menus too. They are all navigating to the correct locations. However the 'Home' button (first) of the menu does not navigate to index.

I have tried including index into the routing but that does nothing but break the website.

Best How To :

I resolved this by adding a url to a node without children and the onclick opens the submenu as standard on the nodes with children:

@foreach (var node in Model.Nodes)
{
    if (node.Children.Any())
    {
        <li>
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">@node.Title<strong class="caret"></strong></a>
            <ul class="dropdown-menu">
                <li>@Html.DisplayFor(x => node)</li>
                @for (int i = 0; i < node.Children.Count; i++)
                {
                    <li>@Html.DisplayFor(x => node.Children[i])</li>
                }
            </ul>
       </li>
    }
    else
    {
        <li>
            <a href="@node.Url">@node.Title</a>
        </li>
    }
}

For anyone who is doing this for the first time as I am, I also added an order tag to arrange my menu items in the order I wanted:

[MvcSiteMapNode(Title = "mytitle", 
                ParentKey =  "home", 
                Key = "experiencevenuesandcircuits", 
                Order = 5)]

MVC 5 - Validate a specific field on client-side

javascript,jquery,asp.net-mvc,validation,asp.net-mvc-5

After digging around in the source code, I've come to these conclusions. First, the purpose of unobtrusive is to wire up the rules and messages, defined as data- attributes on the form elements by MVC, to jQuery.validation. It's for configuring/wiring up validation, not a complete wrapper around it, so when...

How to get routevalues from URL with htmlhelpers or JavaScript?

javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-routing

To write server side code to be processed by razor engine, you have to prepend your statement with @. That will only work if that Javascript is embedded on the view. You can also do it with Javascript. Something like this should do the trick var urlParts = location.href.split('/'); var...

MVC5 Scaffolding Dropdowns Out the Box

asp.net-mvc,asp.net-mvc-5,poco,html.dropdownlistfor,asp.net-mvc-scaffolding

Size and color are lazy loaded by default (virtual) so you need to eagerly load them: var products = context.Products.Include(p => p.Color).Include(p => p.Size).ToList(); https://msdn.microsoft.com/en-us/data/jj574232.aspx If your issue is with the drop downs, you will want to compose a viewmodel in your controller that has the list items, send that...

MVC/Razor: Error at Viewbag.Title

c#,asp.net-mvc,razor,asp.net-mvc-5

Ok, the culprit was this: <ul class="list-inline text-center propertyRegionUL"> <li data-marketid="Miami-Dade" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Miami-Dade" ? "active" : "")">Miami Dade</li> <li data-marketid="Fort-Lauderdale" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() == "Fort-Lauderdale" ? "active" : "")">Fort Lauderdale</li> <li data-marketid="West-Palm-Beach" class="regionLI @(ViewContext.RouteData.Values["id"].ToString() ==...

How to augment actionlink with route values at runtime with JavaScript in ASP.NET MVC 5?

javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing

I'm not sure this is the best way of doing this, but I'll provide you with my solution to this problem. The main idea is to generate the link with all required parameters and format the href with javascript, like string.Format in c#. Generate the link: @Html.ActionLink("Link", "action", "controller", new...

Web API Basic Auth inside an MVC app with Identity Auth

c#,authentication,asp.net-web-api,asp.net-mvc-5

I us a filter attribute to adorn the actions i wanted to expose to Simple Auth. I cant remember where i got this code from (probably stackoverflow i just don't have the link so i cant claim credit for it) public class BasicHttpAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(HttpActionContext...

How to use ajax to post json string to controller method?

jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5

Your action method is expecting a string. Create a javascript object, give it the property "data" and stringify your data object to send along. Updated code: $.ajax({ type: 'post', dataType: 'json', url: 'approot\Test', data: { "json": JSON.stringify(data) }, success: function (json) { if (json) { alert('ok'); } else { alert('failed');...

Entity Type 'AstNode' has no key defined

asp.net-mvc-5,ef-code-first,entity-framework-6

I solved this by examining all of the DbSet definitions. I had pared down the data model while also upgrading it. I had removed the Lookup model class but neglected to also remove the DbSet<Lookup> Lookups { get; set; } property. This resulted in the class being resolved as Microsoft.Ajax.Utilities.Lookup....

LINQ: Searching inside child entities

c#,linq,asp.net-mvc-5

One option would be to use LINQ .Any(): var stringResults = db.Properties.Where(x => x.Address.Contains(id) || /* Other conditions || */ x.BayOptions.Any(g => g.Description.Contains(id))); Here, x.BayOptions.Any(g => g.Description.Contains(id)) will return true if any of the BayOptions values have a description which contains the ID....

knockout.js with kendo UI MultiSelect over MVC 5

javascript,knockout.js,asp.net-mvc-5

HtmlAttributes is the key @(Html.Kendo().MultiSelect() .Name("Profiles") .BindTo(new SelectList(ViewBag.Profiles_msl, "ID", "profiles")) .Value(new[] { new { } }) .HtmlAttributes(new{id="ID", data_bind = "options: Profiles_msl, optionsText: 'profiles', optionsValue: 'ID'" }); ) ...

How to upgrade mvc2 to mvc5?

asp.net-mvc,asp.net-mvc-2,asp.net-mvc-5

I would highly recommend you to create a new empty MVC 5 project, and move all your files there from old MVC 2 project. If you just try to update DLLs its very hard be sure if you updated all DLLs, proj file, nugets, or at least little bit more...

How detailed should your repository be? Testing issues [closed]

c#,unit-testing,asp.net-mvc-5

Welcome to chasing the windmill of 100% test coverage :) You're right, there isn't a ton of value in unit testing a controller method which doesn't actually contain any logic. (Somewhere in the world, Uncle Bob just spilled his coffee.) There is some, though... By explicitly defining the expectations (in...

ApplicationUser ICollection member not being saved in DB

c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5

You need to model your collection items. You could go many to many or one to many. // many to many public class Interest { public int InterestId { get; set; } public string InterestDesc { get; set; } // field can't match class name } // one to many...

How to use more than 1 Model on a page by using asp.net mvc 5?

c#,razor,asp.net-mvc-5

In your layout use Html.Action() or Html.RenderAction() to call a ChildActionOnly method that returns a partial view for LoginModel [ChildActionOnly] public ActionResult Login() { LoginModel model = // initialize the model you want to display in the Layout return PartialView(model); } and create a partial view that displays the links,...

MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?

asp.net-mvc,asp.net-mvc-4,razor,asp.net-mvc-5,claims-based-identity

Your claim identity does not have ClaimTypes.NameIdentifier, you should add more into claim array: var claims = new List<Claim> { new Claim(ClaimTypes.Name, "Brock"), new Claim(ClaimTypes.Email, "[email protected]"), new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid }; To map the information to Claim for more corrective: ClaimTypes.Name => map to username ClaimTypes.NameIdentifier => map...

Why is KnockoutJS not showing the same number of objects as my Web API controller?

knockout.js,asp.net-mvc-5,web-api

ko.observableArray does have a length property, but it is the property of the observableArray function itself, not of the array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length To get the length of the enclosed array, invoke observableArray then call length: self.object().length. For example in your code, change your alert to: alert(xhr + " " + status...

Inherited Property of Model is always returning Null Value

c#,asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-5

You radio button group is not inside the <form> tags so its value is not sent when the form is submitted. You need to move the radio buttons to inside the form (in the partial) and remove the hidden input for property ReportName. If this is not possible you could...

Produce different serialized JSON for a given class in different scenarios

c#,json,serialization,asp.net-mvc-5,json.net

I finally went with a mix of Wrapper classes and the methodology suggested by Raphaël Althaus: use Wrappers where some amount of sophistication may be required and use Raphaël's suggestion when simplicity will do. Here's how I am using wrappers (intentionally left out null checks): public class Entity1View1 { protected...

Convert string value to english word

c#,asp.net-mvc-5

First you need to get the decimal part of the number into a separate integer, then just call your number to words function twice something like this: double value = 125.23; int dollars = (int)value; int cents = (int)((value - (int)value) * 100); Console.WriteLine("{0} dollars and {1} cents", wordify(dollars), wordify(cents));...

Embedding a Silverlight App into a MVC

c#,asp.net-mvc-5,silverlight-5.0

Do you have the Silverlight project added to your MVC project? If you don't you will need to go to your project that is your MVC, right click it and go to properties. Go to silverlight applications then add the project there too. Then try it with your current code...

Convert SQL to linq statement

c#,linq,asp.net-mvc-5

Just use Any(), which will return a boolean, true if your query returns anything, else false. var result =(from a in _applicationRepository.GetList(a => a.ID == applicationId) from r in _roleRepository.GetList(r => r.ApplicationId == a.ID && r.Name == rolename) from au in _authorizationRepository.GetList(au => au.ApplicationId == a.ID && r.ID == au.RoleId)...

MVC: after export to excel, index action result is not getting called

asp.net-mvc-5,export-to-excel

You can't do that I'm afraid, once you have sent the header for the download, you can't then send another set of headers to do the redirect. There is a technique mentioned in this blog post which you can alter to do a redirect when a cookie appears from the...

In RouteConfig, how can I IgnoreRoute for this “Rejected-By-UrlScan” path?

c#,asp.net,asp.net-mvc,asp.net-mvc-routing

My question to you is after you ignore it what do you want to do. The reason we ignore static file paths is to avoid the route module from processing static files such as favicon.ico and instead a normal asp.net request process will proceed. The following code will ignore it...

How do I properly send __RequestVerificationToken with an ajax request in MVC5

ajax,asp.net-mvc,asp.net-mvc-5

x = $.post(window.location, {data: $('#editDrinkForm').serialize()}) is wrong. Do this: x = $.post(window.location, data: $('#editDrinkForm').serialize()) (some credit to stephen's comment)...

string.Format is not giving correct output when INR currency symbol (Rs.) come to display

c#,asp.net-mvc-5,devexpress

Your Model.CurrencySymbol string can have some symbols that can be interpreted as format specifier symbols. You can use literal string delimiter ('string', "string") so your currency symbol string will be copied to the result. For example: column.PropertiesEdit.DisplayFormatString = string.Format("'{0}' #,0.00", Model.CurrencySymbol); //Here comes string delimiters: ↑ ↑ Also you can...

MVC route attribute no controller

asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing

Ok so ranquild's comment pushed me in the right direction. In my route config, I had the default route of routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); So that my homepage would still work on the url with...

Linq Conditional DefaultIfEmpty query filter

c#,linq,asp.net-mvc-5,linq-query-syntax

I solved it by adding the filter after the initial query, checking if the e.PractitionerProfiles were null. var query = from e in _repository.GetAll<Entity>() from u in e.Users where (e.AuditQuestionGroupId != null ? e.AuditQuestionGroupId : 0) == this.LoggedInEntity.AuditQuestionGroupId from p in e.PractitionerProfiles.DefaultIfEmpty() select new { entity = e, user =...

Future plans to consider for asp.net mvc 5.2 web application, with releasing asp.net mvc6 (vnext)

asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-mvc-6,asp.net-mvc-5.2

I would simply recommend following the standard best practice of n-tier architecture and keeping logic related to things like querying a database in class libraries. MVC 6 is drastically different from previous versions, so there's no easy migration. You'll basically need to start a brand new project and move...

EPPlus export model to Excel: System.NullReferenceException

c#,asp.net-mvc-5,epplus

You can't (well certainly SHOULDN'T) try to save directly to a user's filesytem from a web application. I suspect your null reference is somewhere in the Environment.SpecialFolders... object. It woud be better to return the file as a byte array to the response in your controller action. This way the...

Asp.Net MVC 5 + Bootstrap. How make inputs fit screen width?

css,asp.net,asp.net-mvc,twitter-bootstrap,asp.net-mvc-5

The default MVC5 template has a css rule in Site.css: input, select, textarea { max-width: 280px; } I usually remove this rule. It causes problems with Bootstrap v3 input group where the input box does not extend to its container's width....

Web API AuthorizeAttribute does not return custom response

c#,asp.net-web-api,asp.net-mvc-5

You should override the OnAuthorization method, that use the IsAuthorized and flushs the response, or force a flush at your method. Makes more sense fill the response where the filter manipulates It.

Best approach to upgrade MVC3 web app to MVC5?

c#,.net,asp.net-mvc,asp.net-mvc-5

There's a handy documented guide by Rick Anderson which he wrote to upgrade from MVC4, the same applies to you with the exception of the fact that the "Old version" of DLLs he mentions will be different to the ones that you will have, but the outcome will still be...

MVC throwing HTTP 404 error

c#,asp.net-mvc-5

Change the [GET("resetpassword")] to POST because the form from cshtml file use the post method: using (Html.BeginForm("resetpassword", "authentication", FormMethod.Post,.... ...

MVC5 Login to custom Database

asp.net-mvc,authentication,login,asp.net-mvc-5,owin

You can customize your tables, your storage and your classes. The process is not straightforward but with a little bit of work you can do that. I've answered a similar question few days ago. You can find it here. You can find a project on github where I've tried to...

Add azure db to mvc5 project

asp.net,azure,visual-studio-2013,asp.net-mvc-5,sql-azure

I think that you need to create the DB in Azure from the Azure control panel. Once it is there, EF can use the connection string for Azure to add tables/data to an existing DB. Due to the configuration requirements of Azure DB, I haven't found any option but the...

How to append Urls in angular routing?

asp.net,angularjs,asp.net-mvc-5,angularjs-ng-repeat,angular-ui-router

You need to change your $routeProvider.when url option, that will accept two parameter one would be albumType & other would be alubmName. You that you could get those values in your b1Ctrl using $routeParams service. Markup <li ng-repeat="album in albums"> <a ng-href="/albums/{{alubm.type}}/{{album.name}}">{{album.name}}</a> </li> Code when('/albums/:albumType/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl'...

An unhandled exception of System.InvalidOperationException breaks my MVC App?

c#,asp.net-mvc-5,antiforgerytoken

This article might help: Unfortunately this error is a little confusing because it says “nameidentifier or identityprovider” even though you may have one of the two. By default you need both. Anyway, if you’re not using ACS as your STS then the above error pretty much tells you what’s needed...

Getting users from another AD Domain using PrincipalContext

c#,asp.net,active-directory,asp.net-mvc-5,active-directory-group

You need to use the underlying System.DirectoryServices.DirectoryEntry for the group: var groupEntry = (DirectoryEntry)group.GetUnderlyingObject(); (Note: according to MSDN GetUnderlyingObject() will return a DirectoryEntry, even though the return type is object.) From there you can get the member distinguished names: var memberDistinguishedNames = groupEntry.Properties["member"].Cast<string>(); The users from the other domain are...

How to access UrlHelper.Action or similar from within Global asax

c#,routing,asp.net-mvc-5

You need to construct the UrlHelper yourself: var url = new UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes) .Action("YourAction", "YourController", new { paramName = paramValue }); See MSDN...

Store does not implement IUserLockoutStore

asp.net-mvc-5,asp.net-identity

See this answer: When implementing your own IUserStore, are the "optional" interfaces on the class actually optional? You will need to trick or override the method you are trying to call in your store to implement one that does not use the "optional" lockout store. You may be unpleasantly surprised...

Knockout js unable to bind data using observableArray

knockout.js,asp.net-mvc-5

self.Employees.push(data); should be self.Employees(data);

When should I use ViewBag/model?

c#,model,asp.net-mvc-5,viewbag

ViewBag is not faster. In both cases your creating a model of List<MyTable>. All the code you have show for creating your 'MyTable' model is pointless - your just creating a new collection containing duplicates from the existing collection. In the controller it just needs to be public ActionResult MyAction()...

In MVC Razor, how can I correctly add querystring parameters to an html.actionlink?

asp.net-mvc,razor,asp.net-mvc-5

The problem arise from the fact that there is no overload as LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, Object) Use the overloaded method LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, Object, Object) @Html.ActionLink((string)item.Student_Name, "Index", "FourCourseAuditDetails", new { filterByStudent = item.Student_Name}, null) Also need to type cast item.Student_Name to string....

MvcSiteMapProvider MVC5 External URL Re-routing to Home Controller / Index Method

asp.net-mvc-5,mvcsitemapprovider

MvcSiteMapProvider is driven by HTML helpers. Since I cannot reproduce the problem with v4.6.18 and MVC5, I suspect that you have not added one to your view. A typical case would be to add the menu HTML helper to your /Views/Shared/_Layout.cshtml page, as follows. <div class="navbar-collapse collapse"> @*<ul class="nav navbar-nav">...

EPPlus: how can I assign border around each cell after I apply LoadFromCollection?

c#,asp.net-mvc-5,epplus

If I know the amount of columns the model has, I can count the number of rows with a function and do this: var modelRows = exportQuery.Count()+1; string modelRange = "D1:F" + modelRows.ToString(); var modelTable = worksheet.Cells[modelRange]; Or, with more context. I verified that EPPlus will accept a string variable...

How to automatically update the database on application start up

c#,asp.net-mvc,asp.net-mvc-5

you must enable automatic migrations in your context configuration file internal class Configuration : DbMigrationsConfiguration<YourContext> { public Configuration() { this.AutomaticMigrationsEnabled = true; this.AutomaticMigrationDataLossAllowed = false; } ...

Can I use Ninject when setting up my routes?

asp.net-mvc,asp.net-mvc-routing,ninject,ninject.web.mvc

If I get you right, you want to have access to your repository to assign Article names to your urls. It can be done, but first, think about what you've just wrote here: [Inject] public SectionsRepository<Section> Repository { get; set; } The [Inject] attribute tells the framework that any property...

MvcSiteMapProvider - Enhanced bootstrap dropdown menu

c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap

node.Descendants should be node.Children Learn the difference on Descendants and Children here, CSS Child vs Descendant selectors (Never mind the post beeing about CSS, this is a generic pattern)...