asp.net-mvc-5,asp.net-mvc-routing,mvcsitemapprovider , MvcSiteMapProvider “Home” button in menu not working onclick


MvcSiteMapProvider “Home” button in menu not working onclick

Question:

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.


Answer:

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)]

Related:


MVC throwing HTTP 404 error


c#,asp.net-mvc-5
I am completely stuck and confused why it works with one View to Controller but not the other one. The one that works: public class HomeController : Controller { // GET: Home IAuthenticationManager Authentication { get { return HttpContext.GetOwinContext().Authentication; } } public ActionResult Index() { return View(); } [POST("login")] [ValidateAntiForgeryToken]...

Best approach to upgrade MVC3 web app to MVC5?


c#,.net,asp.net-mvc,asp.net-mvc-5
I have a web application which runs on Azure which is currently running MVC3/C#, EF6.1, .NET4.5. I would like to upgrade it to MVC5 to be: a) Current b) Get benefit of new features c) Get Performance gains. This is a part of a performance project, so hopefully there will...

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


c#,asp.net-mvc-5,devexpress
While display bank transaction data to INR currency symbol (Rs.), output is not coming correct way. I need to display currency symbol along with 2 decimal points with thousand separator. I have tried so far1: column.PropertiesEdit.DisplayFormatString = string.Format("{0} #,0.00", Model.CurrencySymbol); I have used DevExpress MVC GridView. Current output when INR...

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


jquery,asp.net-mvc,visual-studio-2013,asp.net-mvc-5
I want to be able to post a json string to a control action but it's always receive the string as null. If I create a view model for the controller method, it works, but that's not what I want since there will be too much view models to maintain....

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


c#,asp.net-mvc-5,antiforgerytoken
I am taking the concept of building a OWIN login from a empty MVC and I am just starting to add the part with using my database to login the user after creating a Identity claim to put in the URL. This is my code to create the claim to...

When should I use ViewBag/model?


c#,model,asp.net-mvc-5,viewbag
I think that using ViewBag is faster than model. My example is: In the action: public ActionResult MyAction() { ViewBag.Data = (from m in myDatabase.myTable select m).ToList(); } In the view: @foreach(var item in ViewBag.Data) { <tr> <td>@item.myColumn</td> </tr> } By using model: [Table("tbl_mytable")] public class MyTable() { public int...

Can I use Ninject when setting up my routes?


asp.net-mvc,asp.net-mvc-routing,ninject,ninject.web.mvc
I have an ASP.NET MVC5 web site that uses Ninject. The site is for an online magazine. What I would like to do is set up some routes, but pull the data from an injected repository. So, I would like to have routes like these... routes.MapRoute("Section9", "Section9_Ask-the-professional", new {controller =...

Knockout js unable to bind data using observableArray


knockout.js,asp.net-mvc-5
I am trying to display all the employees in the database and I am unable to achieve it. My JS, var EmployeeKoViewModel = function () { var self = this; self.EmpId = ko.observable(""); self.Name = ko.observable(""); self.City = ko.observable(""); self.Employees = ko.observableArray([]); GetEmployees(); function GetEmployees() { $.ajax({ type: "GET", url:...

Getting users from another AD Domain using PrincipalContext


c#,asp.net,active-directory,asp.net-mvc-5,active-directory-group
How would I get users from an AD Group which contains users from different domains. For example, I have 2 domains in my active directory, Domain1.corp.com and Domain2.corp.com I have an AD group called TestGroup which contains users from both the domains. Domain1 users: TestUser1, TestUser2 Domain2 users: TestUser3, TestUser4,...

ApplicationUser ICollection member not being saved in DB


c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5
I've added some properties to ApplicationUser, and two of them are ICollection's. When I use Update-Database it doesn't generate columns for these two members. So, what am I missing here? I imagine it's very basic. I'm used to working with Hibernate in Java, where it generates a new table for...

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


asp.net-mvc,razor,asp.net-mvc-5
I have an MVC Razor page where I am trying to add a querystring parameter to the URL. <td> @Html.ActionLink(item.Student_Name, "Index", "FourCourseAuditDetails", new { filterByStudent = item.Student_Name}) </td> My desired outcome is: http://[server]/FourCourseAuditDetails/Index?filterByStudent="[item.Student_Name]", but when I test out the page, the anchor href attirubte looks like this: http://[server]/[route of current...

LINQ: Searching inside child entities


c#,linq,asp.net-mvc-5
I have 'Property' objects with 'BayOption' child objects. I need the site search to search through the child BayOptions as well as the Properties and return Properties if the search criteria matches the child or parent. A Property can have multiple BayOptions (and usually does). I was unsure if .Select...

Web API Basic Auth inside an MVC app with Identity Auth


c#,authentication,asp.net-web-api,asp.net-mvc-5
So I have a C# MVC app using Identity for its authentication. I now have a need to expose a few things via Web API to some of my clients. Instead of building a separate app, project, deployment... I've simply added an API Controller to my existing project. To keep...

Web API AuthorizeAttribute does not return custom response


c#,asp.net-web-api,asp.net-mvc-5
How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

How to append Urls in angular routing?


asp.net,angularjs,asp.net-mvc-5,angularjs-ng-repeat,angular-ui-router
How to do url(string) cocatenation in angular routing. Please refer the below snippet to understand my question. app.config(['$routeProvider', '$location'], function($routeProvider) { when('/', { templateUrl: '/AlbumsList.html', controller: 'a1Ctrl' }). when('/albums/:albumName', { templateUrl: 'AlbumsList.html', controller: 'b1Ctrl' }) }) app.controller('a1Ctrl', function($scope, $http) { $scope.albums = function() { //ajax getting data from server }...

knockout.js with kendo UI MultiSelect over MVC 5


javascript,knockout.js,asp.net-mvc-5
Currently I have the following code, MVC with knockout bindings (this works fine) @Html.DropDownListFor(m => m.profiles, (SelectList)Model.profileItems, new { id = "ID", data_bind = "options: Profiles_msl, optionsText: 'profiles', optionsValue: 'ID'" }) I also have this which is kendo UI with MVC model bindings (no knockout). This also works. @(Html.Kendo().MultiSelect() .Name("Profiles")...

Inherited Property of Model is always returning Null Value


c#,asp.net,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-5
I have a view which displays a radiobutton list on left side of the page and it also loads a partialview on right side of the page which consist of various filters to be selected before displaying a report in a popup window. The problem is that the property named...

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


c#,unit-testing,asp.net-mvc-5
In my controller, I have something like this: class HomeController { [AllowAnonymous] public ActionResult Index() { HomeViewModel viewModel = new HomeViewModel(); viewModel.FieldSearchCriteria = new SearchCriteria(); viewModel.Blogs = this.unitOfWork.BlogRepository.GetAllPublishedBlogs(1, 2, "PublishDate", SortDirection.DESC, null).ToList(); viewModel.FieldWanteds = this.unitOfWork.FieldWantedRepository.GetAllFieldWanteds( 1, 2, "CreatedAt", SortDirection.DESC, null ).ToList(); viewModel.Fields =...

MVC5 Login to custom Database


asp.net-mvc,authentication,login,asp.net-mvc-5,owin
What if you have your own database and a BAL (Business Access Layer) and don't want to use DefaultConnection and the template ASPNET database tables but my own user tables? How can you use a custom database? ConnectionString: public class AppDbContext : IdentityDbContext<AppUser> { public AppDbContext() : base("DefaultConnection") { }...

MVC route attribute no controller


asp.net-mvc,asp.net-mvc-5,asp.net-mvc-routing
I'm building an intranet where I have the following home controller: [Route("{action=index}")] public class HomeController : Controller { public ActionResult Index() { return View(HomeModelBuilder.BuildHomeModel()); } public ActionResult FormsHome() { return View(HomeModelBuilder.BuildFormsHomeModel()); } } I'm trying to get my forms homepage to have a url of http://intranet/forms so I thought I...

MVC 5 - Validate a specific field on client-side


javascript,jquery,asp.net-mvc,validation,asp.net-mvc-5
I want to populate a city/state drop down list based on the postal code a user types into a textbox. So when the text changes, I'm going to make an ajax call to retrieve the data. However, I only want to perform that ajax request for valid postal codes. The...

Embedding a Silverlight App into a MVC


c#,asp.net-mvc-5,silverlight-5.0
I decided to convert the WPFs into a Silverlight applications. My only problem is trying to get it to display the silverlight application in my MVC web browser. I added all of my silverlight projects into my MVC project. I am just not getting it to show my silverlight application....

EPPlus export model to Excel: System.NullReferenceException


c#,asp.net-mvc-5,epplus
I have an MVC view that correctly displays a model. Now that I have been asked to put an Export to Excel function on that page, I heard about EPPlus and gave it a try. From this site I thought I had something that would simply do the job. After...

How to upgrade mvc2 to mvc5?


asp.net-mvc,asp.net-mvc-2,asp.net-mvc-5
I've got an old project from a friend that he wants me to do redo. How ever that project is written in ASP.net mvc2. So When I try to open it in visual studio 2013 I can errors. Saying the file is incompatible. How would I go ahead and fix...

MvcSiteMapProvider - Enhanced bootstrap dropdown menu


c#,twitter-bootstrap,asp.net-mvc-5,mvcsitemapprovider,mvcsitemap
I'm trying to build a menu like this: For reference I'm using this library https://github.com/behigh/bootstrap_dropdowns_enhancement @Html.MvcSiteMap().Menu("BootstrapMenuHelperModel") @model MenuHelperModel <nav class="navbar" role="navigation"> <div class="container-fluid menu-container"> <div class="collapse navbar-collapse"> <div class="navbar-header"> <span class="navbar-brand">FAR BACKOFFICE</span> </div> <ul class="nav nav-pills"> @foreach (var node in Model.Nodes) { if...

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


c#,razor,asp.net-mvc-5
I want to use 2 models. The first is on Index.cshtml page, and the second is on _Layout.cshtml page In the controller which contains the action public ActionResult Index(){...}, I declare some values and return it to View(). Like this: public ActionResult Index() { HomePageViewModel model = new HomePageViewModel(); //...

Convert string value to english word


c#,asp.net-mvc-5
I'm trying to figure out / where to start in regards to this situation say for example I enter $127.45 in to a textbox I would expect the application to spit back one hundred and twenty-seven dollars and forty-five cents The word will then be placed on a document and...

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


css,asp.net,asp.net-mvc,twitter-bootstrap,asp.net-mvc-5
I really don't know what I'm doing wrong. I want my textboxes with same size of my buttons below. I already tried change a lot in the cshtml but without success. Below my cshtml file: @model SomeModel.Models.LoginViewModel <div class="row"> <div class="col-md-8 col-sm-12 col-xs-12"> <section id="loginForm"> @using (Html.BeginForm("Login", "Account", new {...

Entity Type 'AstNode' has no key defined


asp.net-mvc-5,ef-code-first,entity-framework-6
I'm porting a data model from EF4 to EF6 Code First. I'm getting the following message when the database creation is attempted. I'm at a loss to understand what is causing this. I don't have any Context, AstNode or JSParser entities. It is also not looking in the Models namespace:...

MVC5 Scaffolding Dropdowns Out the Box


asp.net-mvc,asp.net-mvc-5,poco,html.dropdownlistfor,asp.net-mvc-scaffolding
I want to view, edit and create with drop-down list of my lookup relationships. Sometimes this works, sometimes it doesn't. It's a mystery that I'm hoping can be definitely solved here. Here's my POCO's for the lookup public class Color { public int Id { get; set; } public string...

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


c#,routing,asp.net-mvc-5
I am trying to prepare a 301 redirect for a typo I made 'recieved' I am struggling to find a way of getting the url from the action and controller names. I am aware of UrlHelper.Action but it does not exist within Global.asax. How do I gain access to this...

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


knockout.js,asp.net-mvc-5,web-api
The solution was the same as in this question: How to get an observableArray's length? ...but the question itself is unique so anyone in the same situation will hopefully have an easier time finding the answer than I did. I'm fairly new to Knockout and to Web API. I've built...

Store does not implement IUserLockoutStore


asp.net-mvc-5,asp.net-identity
I'm trying to implement own DAL for asp.net Identity 2.0 with functionality that I need. I don't need Account Lockout functionality. But When I try to call var result = await SignInManager.PasswordSignInAsync(model.Login, model.Password, model.RememberMe, shouldLockout: false); I get System.NotSupportedException:Store does not implement IUserLockoutStore<TUser>. So why should I need to implement...

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 need to get any ideas of how i should be managing our previous asp.net MVC 5.2 web application.. now i am using asp.net mvc-5.2 with entity framework 6.0. and i want to start phase-2 for some of these projects. so should i consider upgrading my mvc 5.2 to be...

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


c#,asp.net-mvc-5,epplus
In my export ActionResult I was able to load the model into my ExcelPackage. Where I am having trouble is assigning a border around each cell once LoadFromCollection is applied. While the AutoFitColumns correctly applies, the border style I applied only works on Cells["D1"], but not on the table. BorderAround...

Add azure db to mvc5 project


asp.net,azure,visual-studio-2013,asp.net-mvc-5,sql-azure
I have a MVC 5 project using visual studio 2013. How can I add/create a database in azure from visual studio so that EF6 code first can just use and create the models? I've been browsing server explorer but there is nothing there related to azure....

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


asp.net-mvc-5,mvcsitemapprovider
I'm using MvcSiteMapProvider 4.6.18. Many of my menu items link to external sites; however, the "url" attribute of mvcSiteMapNode is not being carried over to the menu. That is, I can see the url in the source, but the link is referring to the parent mvcSiteMapNode controller and action and...

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
I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View. Error: A claim of type...

Linq Conditional DefaultIfEmpty query filter


c#,linq,asp.net-mvc-5,linq-query-syntax
I have a query as below: bool variable = false//or true 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 = u, profile = p }; This...

Produce different serialized JSON for a given class in different scenarios


c#,json,serialization,asp.net-mvc-5,json.net
Update 1: for reasons I won't go into, I want to avoid having anything other than the properties to be persisted in my entity objects. This means no extra properties or methods... I have an entity called Entity1 with (say) 10 public properties. In one place in my code I...

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


asp.net-mvc-5,export-to-excel
I have one MVC application, in which export to excel functionality is given. I want to redirect Index action once export is finished. I have written below code but it not redirected to index action. what i missed here ? output = new MemoryStream(); workbook.Write(output); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",...

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


ajax,asp.net-mvc,asp.net-mvc-5
I'm trying to send an ASP.NET AJAX request to my application. In the application's controller, I have: [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Instructions,Glass,Notes")] Drink drink, [Bind(Include= "ID,Amount,Brand,IngredientID,DrinkID")] IEnumerable<DrinkIngredient> DrinkIngredients) { if (ModelState.IsValid) { //and so on my javascript looks like this: console.log($('#editDrinkForm').serialize()) var x = new XMLHttpRequest(); x...

How to get routevalues from URL with htmlhelpers or JavaScript?


javascript,asp.net,asp.net-mvc,asp.net-mvc-5,asp.net-routing
I have this MVC MapRoute routes.MapRoute( name: "Authenticated", url: "{controller}/{action}/{foo}/{bar}", defaults: new { controller = "Home", action = "WelcomePage", Foo = "0", Bar = "0" } ); And URL http://localhost/mysite/controller/action/2/1 How can I with JavaScript recieve the 2 and 1? I would prefer a solution with as little substring work...

MVC/Razor: Error at Viewbag.Title


c#,asp.net-mvc,razor,asp.net-mvc-5
I have two methods: public ActionResult Index() { var propList = db.Properties .Where(x => x.SiteVisibilityFlags.HasFlag(Enums.SiteVisibilityFlags.Corporate) || (x.SiteVisibilityFlagsOverride == true && x.SiteVisibilityFlagsOverrideValue.HasFlag(Enums.SiteVisibilityFlags.Corporate))) // just ones visible to 'Corporate' .ToList(); // Use view model var pDVMs = DomainModelsToViewModels(propList); return View(pDVMs); } public ActionResult Region(string id) // (regionId/marketId) { // make sure to...

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


c#,asp.net,asp.net-mvc,asp.net-mvc-routing
I'm trying to apply an IgnoreRoute to a path that contains "Rejected-By-UrlScan", and don't understand the syntax. The MSDN documentation here provides no examples. https://msdn.microsoft.com/en-us/library/system.web.mvc.routecollectionextensions.ignoreroute(v=vs.118).aspx Here is an example path that I'm dealing with: http://example.com/Rejected-By-UrlScan?~/Content/fonts/glyphicons-halflings-regular.woff2 These are some IgnoreRoute examples that I've picked up, but all of these are directly...

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 have this ActionLink. @Html.ActionLink("Link", "action", "controller", null, htmlAttributes: new {@class = "menuLink"}) I have to set routeValues to null because I don't know the value at compiletime. They are recieved from the selectedvalue of some dropdowns at runtime. Hence, I am trying to augment the routevalues at runtime with...

How to automatically update the database on application start up


c#,asp.net-mvc,asp.net-mvc-5
A run time error occurs when i run my code asking me to do a code migration to update my database. I am not sure how to do this, can anyone help me? The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First...

Convert SQL to linq statement


c#,linq,asp.net-mvc-5
I would like to convert the SQL syntax below to a linq statement to get a single boolean result back. The SQL is checking if a user exists in a current role. select case when exists (select 1 from Global.Application as a join Global.Role as r on a.ID = r.ApplicationId...