Skip Navigation LinksHome > Articles > Asp .Net MVC > ASP .NET MVC Preview 5 - Dynamic Action Links

ASP .NET MVC Preview 5 - Dynamic Action Links

Explains How To Create Dynamic Action Links On Data Coming From Database

By Keyur   On   Thursday, 11 September 2008

Page Views : 8486   |   Technologies : Asp .Net MVC

Rating : Rated :
0

Hello Again,

 

In last article we saw how we can fetch data from database and display inside the view page. In this article we will dig more on this and take complexity to one more level and instead of only displaying data we will create actions links from incoming data and using that action link we will bring data from the database and display on other view.

 

Let’s consider a scenario of the previous article’s application which is a simple favorite management system. Once user is registered and we take it for granted that there is some data as well for this user inside the database. Once he/she logs in we have to show them list of categories he/she has created for storing favorites.

 

In this we will have to create two views and add two methods in AccountController.cs file to support these two views. Let’s start by adding two views named Categories.aspx and Links.aspx files. These views have to be added under Account folder. Take a look at following screen shots.

 

1)     Add New MVC Content Page

2)    Two Views Added(Categories/Links) 

Now let’s add two actions to our AccountController.cs file to handle outputs of these two views. Take a look at the code below. At this point I assume that you guys have already created data context using your LINQ TO SQL classes and already have modified the application to be integrated with our custom database. If not please refer to the article below for more details.

 

ASP .Net MVC - Custom Login

ASP .Net MVC – Modify Look & Feel of the Application

ASP .Net MVC – Showing Tabular Data

 

Ok now as you have already added LINQ to SQL classes in your application let’s go ahead and add following two methods inside your AccountController.cs file.

 

public ActionResult Categories()

        {

 

            string username = User.Identity.Name.ToString();

            LinkMVCDataContext lm = new LinkMVCDataContext();

            var uid = from m in lm.Users

                      where m.Username == username

                      select m.UserId;

            string userid = uid.ToString();

            var categories = from cat in lm.Categories

                             where cat.UserId == uid.ToList().First()

                             select cat;

 

            return View("Categories", categories.ToList());

        }

           

Let’s try to understand what we did in this method. The process flow is once the user is logged into the system he/she will be redirected to the categories view where he/she should see all the categories he created for managing their favorites. The trick is when we display these categories we have to show them as hyper link where they can click and drill down to their favorites stored under different categories.

 

So what we did here is created a new data context and selected the user id of the user who is logged in. The next we did is we selected categories from the lnkCategories table stored with that user id.

 

var categories = from cat in lm.Categories

                             where cat.UserId == uid.ToList().First()

                             select cat;

 

Finally what we did is return the view with list of all the categories resulted in our select statement. Next is to modify the categories view. Take a look at the code below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using LinkMVC.Models;

 

namespace LinkMVC.Views.Account

{

    public partial class Categories : ViewPage<List<LinkMVC.Models.Categories>>

    {

    }

   }

 

As you can see here this is our categories.aspx.cs page where it is using reference to Models from our application as well as the page is type of ViewPage with strongly typed Model categories. Now take a look at the aspx page as most of the logic is inside this page with MVC.

 

<%@ Import Namespace="System.Web.Mvc" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

<table cellpadding="0px" cellspacing="0px">

<tr>

<td>

<div class="category">

<%foreach (var category in ViewData.Model)

{ %>

<li id="<%=category.CategoryName%>">

<%=Html.ActionLink(category.CategoryName,"Links",new{id=category.CategoryName })%>

</li>

<%} %>

</div>

</td>

<td style="width: 10px;">

</td>

<td>

<div class="links"> 

</div>

</td>

</tr>

</table>

   </asp:Content>

 

 What we did here is we added a reference to our Namespace="System.Web.Mvc" class and then we looped through every single category in our ViewData.Model to find out about categories and then we dynamically created  “<li>” Html tag and finally we added action link between <li> elements. The action link is the tricky part. We took category name coming from the database attached it with the action “Links” as id to that action.

 

Once you run the application and log in using proper credentials you should be redirected to the categories view and it should look something like below.

One interesting thing to note here is the bottom of the page when you hove over the categories being displayed on the page. I have attached the screen shot for this when I hover over the LINQ category on my page. I should see something like below.

 

And that is where you can see your action link is being created. Remember the id we passed onto the “Links” view in the categories.aspx page above. That is being interpreted dynamically as the action link for that data item. Now we have the action link ready let’s create action itself and view to handle output of that action. Modify your links view as below.

 

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Links.aspx.cs" Inherits="LinkMVC.Views.Account.Links" %>

<%@ Import Namespace="System.Web.Mvc" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

<table cellpadding="0px" cellspacing="0px">

<tr>

<td>

<div class="category">

 

</div>

</td>

<td style="width: 10px;">

</td>

<td>

<div class="links">

<%foreach (var link in ViewData.Model)

{ %>

<li>

<a href="<%=link.ActualUrl%>"><%=link.ActualUrl%></a>

</li>

<%} %>

 

</div>

</td>

</tr>

</table>

</asp:Content>

 

As you see here I am getting list of links from the links table and from that links object I am reading actual URL column and binding it to the <a href=””></> and also setting its text property to be the actual url. If you want you can modify this and add some other comment or something you want to display as the text. I prefere to display the actual url as the text for better redeability. Now let’s check how our Links action looks like.

 

public ActionResult Links(string id)

        {

 

            LinkMVCDataContext lm = new LinkMVCDataContext();

            var ids = from cat in lm.Categories

                     where cat.CategoryName == id

                     select cat.CategoryId;

 

            var links = from lnk in lm.Links

                    where lnk.CategoryId == Convert.ToInt32(ids.ToList().First())

                        select lnk;

            return View("Links", links.ToList());

        }

 

It is a very simple LINQ query which selects all links for the category that is being passed as id to the method. You remember that link we were seeing at the  bottom of the page. The id will be taken from that link and pass to this method as id. Using that id we are selecting all the links from the table and return list of the same.On the view page we are just looping through this list and displaying actual links. Now run the application and click on your favorite category. You should see something like below. I clicked on ASP .Net from above screen.

 

To see all these in action you can also view following two small videos I have created for better understanding. The source code for the application is also attached with this articles.

PART -I

PART -II

 

Thanks

 


Keywords :
Tags :
Rate This Article :

Comments :

# 1 Annonymous Wrote on 09/26/2008


give the sample tutorial video from a-z creation



# 2 Keyur Wrote on 09/26/2008


We are currently working on making videos available for download.You can send email to admin@a2zdotnet.com and we will inform you once the video download is available.For now you can take a look at attached sample code. Sorry for inconvenience.



# 3 Annonymous Wrote on 10/09/2008


good



# 4 Annonymous Wrote on 12/16/2009


I have only one question about the way you created the links. Should you use HTML.Encode(link.ActualURL)? I mean href="<%=HtmlEncode(link.ActualURL)%>"><%=HtmlEncode(link.ActualURL)%>



Write a Comment / Question / Feedback ...


User Login
Username :
Password :
Register Login

Forgot Password


Related Articles