Creating navigation with routed URL in ASP.NET MVC

I'm having trouble with the navigation in asp.net mvc and handling URLs.

For example, when you visit your profile on Facebook, the URL is facebook.com/yourusername. On your profile page, there is a menu with links such as Timeline, About, Friends, etc.

If you click on a link like Photos, the URL changes to facebook.com/yourusername/Photos, and the photos are displayed. The menu remains visible, along with the profile picture and cover photo. It's almost like a partial view has been rendered for viewing the photos.

I would like to achieve this same effect in my project, but I'm not sure how to implement it. I have tried using Partial view, but the problem is that the URL does not change when the partial view is rendered.

How should I structure this in my project?

Here is an example of what my Index.cshtml file, belonging to the Home-controller, looks like:

<div class="centering col-lg-7 logged_in_mainboxes" style="padding: 0; position: relative">

    <div class="col-lg-12 coverPicture" style="background-image: url('/Content/Images/@Model.CoverPicture');">
       <div id="image-cropper">
            <div class="cropit-preview"></div>         
            <h3 class="coverPicTextStyle">
                @Model.Name
            </h3>
            <button type="submit" id="uploadCoverpicture" class="btn_style_2 btn" style="position: absolute; bottom: 10px; right: 10px;">Upload</button>
            <button type="submit" id="crop" class="btn_style_2 btn" style="position: absolute; bottom: 50px; right: 10px; display: none;">Done</button>
            <input type="file" class="cropit-image-input" id="coverUpl" style="display: none;" />
        </div>
        <div class='progress' id="progress_div">
            <div class='bar' id='bar1'></div>
            <div class='percent' id='percent1'></div>
        </div>
        <input type="hidden" id="progress_width" value="0">
    </div>
    <div class="col-lg-12 pull-left">
        <div class="user_menu">
            <ul>
                <li>@Html.ActionLink("Wall","Wall","Home")</li>
                <li>@Html.ActionLink("Music", "Music", "Home")</li>
                <li>@Html.ActionLink("Photos", "Photos", "Home")</li>
                <li>@Html.ActionLink("Videos", "Videos", "Home")></li>
                <li>@Html.ActionLink("About", "About", "Home")</li>
            </ul>
        </div>
    </div>
    <div class="col-lg-7 pull-left" style="margin-top: 15px;">

    </div>
    <div class="col-lg-3 pull-right" style="border-left: 1px solid #ddd; margin-top: 15px; ">
        asdasd
    </div>
</div>

Answer №1

To start organizing the methods associated with the user, it is recommended to group them within a dedicated UserController. This controller can include methods such as:

public ActionResult Index(string username)
public ActionResult Photos(string username)
public ActionResult Music(string username)

Furthermore, set up routing configurations as discussed in your previous inquiry. Create a separate layout page named _UserLayout.cshtml to be used for each of these methods. Each corresponding view should include:

@{ Layout = "~/Views/Shared/_UserLayout.cshtml"; }

To effectively pass the username throughout (to the layout and subsequently to the methods via ActionLink() methods), establish a base class like so:

public class UserBaseVM
{
    public string UserName { get; set; }
}

All models utilized in these methods should inherit from this base class; for instance:

public class UserPhotosVM : UserBaseVM
{ 
    public List<YourPhotoModel> Photos { get; set; }
    ....

Within _UserLayout.cshtml, leverage the UserName property of UserBaseVM to construct your links:

@model yourAssembly.UserBaseVM
... //include common menu/navigation elements
<div class="col-lg-12 pull-left">
    <div class="user_menu">
        <ul>
            <li>@Html.ActionLink("Photos", "Photos", new { userName = Model.UserName })</li>
            ....

In line with a cleaner and more adaptable approach, consider creating a [ChildActionOnly] method that outputs a partial view of the menu, like so:

[ChildActionOnly]
public ActionResult Menu(string userName)
{
    UserBaseVM model = new UserBaseVM(){ UserName = userName });
    ....
    return PartialView(model);
}

Within the _UserLayout.cshtml file, implement:

@{ Html.RenderAction("Menu", new { userName = Model.UserName });

Answer №2

To optimize your application, consider incorporating routes into the design.

Begin by creating a class called "RouteConfig" and include using System.Web.Routing;

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        var route = routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "YourController", action = "Index", id = UrlParameter.Optional },
            namespaces: new string[] { "YourDomain.NameSpace.Controllers" }
        );
        route.DataTokens["UseNamespaceFallback"] = true;
    }
}

Incorporate these routes in your Global.asax file within the Application_Start() method:

RouteConfig.RegisterRoutes(RouteTable.Routes);

Integrate the Session feature to efficiently redirect logged-in users within your application using the OnAuthorization method in the base controller.

If utilizing partial view pages, use:

@Html.Partial("_YourPartialViewPage", Model)

For passing data to the controller, opt for Ajax calls in your JavaScript methods.

yourAjax({ url: '@Url.Content("~/YourController/YourControllerAction")', data: { headerId: id, }, success: successFunction });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to interact with a specific button using Javascript

I need to use jQuery to target the button below: <button id="mybutton" book_title="{{$book->title}}" author="{{$book->author}}" idx="{{$book->id}}" class="btn btn-success b_r_20 btn-xs pull-right" > ...

Utilize clipboard functionality in automated tests while using Selenium WebDriver in conjunction with JavaScript

How can I allow clipboard permission popups in automated tests using Selenium web driver, Javascript, and grunt? https://i.stack.imgur.com/rvIag.png The --enable-clipboard and --enable-clipboard-features arguments in the code below do not seem to have an ...

Retrieve elements from an array based on the value of an object

I have a list of items that resembles the following structure: var entries = [ { sys: {id:"1"}, fields: "article1" }, { sys: {id:"2"}, fields: "place1" }, { sys: {id:"3"}, fields: "offer2" }, { sys: {id:"1"}, fields: "article2" }, { sys: {id:"1" ...

I am attempting to verify a user's login status with Next.js and Supabase, however, I am encountering difficulties in making it function properly

I recently cloned this repository from https://github.com/vercel/next.js/tree/canary/examples/with-supabase-auth-realtime-db and I'm trying to implement a navigation bar that changes based on the user's login status. Unfortunately, the code I&ap ...

Extracting textual information from Wikipedia through iframes?

Currently, I am working on a website project utilizing Squarespace. This site will feature multiple pages dedicated to individuals who have reached a level of notability worthy of having their own Wikipedia page. With over 150 pages planned, manually writi ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Is Chrome not displaying any notification pop-up when I submit a form and then click the back button?

Recently, I've been experiencing some issues with Chrome as it seems to be acting up day by day. Specifically, when using my ASP.NET application, a peculiar behavior occurs. After a user performs a POST action and then clicks on a link for a GET actio ...

Tips for continuing code execution in an ajax success function following the completion of a nested ajax call within the success block

I am facing an issue with a function that utilizes $.ajax. In the success section of the function, I have three nested functions. The first one executes properly, but the second one contains another $.ajax call. While the internal $.ajax call works fine, t ...

Looping through items using v-model value in v-for

My website features a small form that allows users to submit new photos and view previously submitted photos. Users begin by selecting an album for the photo and then uploading it. Currently, I am encountering an issue in retrieving photos based on the sel ...

Angular custom filter applied only when a button is clicked

I have recently started exploring angular custom filters and I am curious to know if there is a way to trigger the filters in an ng-repeat only upon clicking a button. Check out this example on jsfiddle : http://jsfiddle.net/toddmotto/53Xuk/ <div ...

``Toggling all classes in a click event instead of toggling the correct block

Within my collapsed/collapsible blocks, the first block is open while the second and third are closed. The opening and closing function works correctly, but I am struggling to figure out how to change the icons so that they update only for the relevant blo ...

Arrange the objects in the array in React based on their time and date of creation

As a newcomer to the world of React.js and Redux, I am faced with an array of objects structured like this: quizList = [ { createdDate : 1543314832505, id:5bfd1d90d4ed830001f589fc, name:'abc'}, { createdDate : 1543314152180, id:5bfd1ae8d4ed83000 ...

"Trouble with script: external JavaScript file failing to run

The issue lies in the fact that the specified external JavaScript file is not being executed: <script src="//www.google-analytics.com/cx/api.js?experiment=YOUR_EXPERIMENT_ID"></script> Even when I try to directly access the URL, it downloads ...

Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out. Using the prodInfo variable, the input data looks something like this: 2,5k ...

typescript array filter attributes

I encountered a situation where I had 2 separate arrays: items = [ { offenceType:"7", offenceCode:"JLN14", }, { offenceType:"48", offenceCode:"JLN14", } ]; demo = [ { offenceCode: 'JLN14&apo ...

Optimal approach for organizing a mysql+nodejs+express application

In my development process, I typically utilize mysql without sequelize. To establish the database connection, I usually create a module.export function that can be required in other files. Here's an example: var db; module.exports={ getConnection = f ...

Save the outcome of an ArrayBuffer variable into an array within a Javascript code

I'm in the process of developing an offline music player using the HTML5 FileReader and File API, complete with a basic playlist feature. One challenge I'm facing is how to store multiple selected files as an ArrayBuffer into a regular array for ...

Explore our product gallery with just a simple hover

I am looking to design a product list page with a mouseover gallery similar to the one showcased on [this page][1]. I attempted to use a vertical carousel like the one illustrated in this Fiddle, but unfortunately, it does not function like Zalando and jc ...

Maximizing Efficiency with Selenium: Leveraging the Page Object Pattern and Page Factory

After spending a year developing my Project from scratch, I have reached a certain level of maintenance with my Framework and tests. However, as each day passes, I find myself questioning whether I am implementing good practices in my Project. It would gre ...