Skip Navigation LinksHome > Articles > Asp .Net MVC > MVC Preivew 4 & LINQ - Display Data Using LINQ On MVC Application

MVC Preivew 4 & LINQ - Display Data Using LINQ On MVC Application

Expalins how to display tabular data on ASP .Net MVC Page using LINQ

By Keyur   On   Friday, 05 September 2008

Page Views : 2698   |   Technologies : Asp .Net MVC

Rating : Rated :
0

Hi,

 

In previous two articles of this series we looked at customizing login functionality for our own database instead of asp.net services and also we saw how we can modify look and feel of the MVC application using CSS and images. In this article we will modify our registration page’s look and feel as well as incorporate custom registration with our requirements. First let’s  modify the look and feel of the registration page. Open your project and your registration page so that it looks something similar to this.

   1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="LinksMVC.Views.Account.Register" %>
   2: <asp:Content ID="registerContent" ContentPlaceHolderID="MainContent" runat="server"><br /><br />
   3: <form method="post" action="<%= Html.AttributeEncode(Url.Action("Register")) %>">        
   4:         <div>
   5:         <table cellpadding="0px" cellspacing="0px">
   6:             <tr>
   7:                 <td class="regleft">
   8:                 </td>
   9:                 <td class="regrepeat">
  10:                     <table>
  11:                      <tr>
  12:                             <td class="lbls" colspan="2">                               
  13:                                 Welcome To Favourite Registration
  14:                                <br />
  15:                                <br />
  16:                             </td>
  17:                             </tr>
  18:                         <tr>
  19:                             <td class="lbls">
  20:                                 Username:
  21:                             </td>
  22:                             <td class="ctrls">
  23:                                <%= Html.TextBox("username") %>
  24:                             </td>
  25:                         </tr>
  26:                         <tr>
  27:                             <td class="lbls">
  28:                                 Email:
  29:                             </td>
  30:                             <td class="ctrls">
  31:                                <%= Html.TextBox("email") %>
  32:                             </td>
  33:                         </tr>
  34:                         <tr>
  35:                             <td class="lbls">
  36:                                 Password:
  37:                             </td>
  38:                             <td class="ctrls">
  39:                                <%= Html.Password("password") %>
  40:                             </td>
  41:                         </tr>
  42:                         <tr>
  43:                             <td class="lbls">
  44:                                 Confirm Password:
  45:                             </td>
  46:                             <td class="ctrls">
  47:                                <%= Html.Password("confirmpassword") %>
  48:                             </td>
  49:                         </tr>                       
  50:                         <tr>
  51:                             <td class="ctrls">
  52:                               
  53:                             </td>
  54:                             <td>
  55:                             </td>
  56:                         </tr>
  57:                         <tr>
  58:                             <td>
  59:                             </td>
  60:                             <td>
  61:                                 <input type="submit" value="Register" />
  62:                             </td>
  63:                         </tr>
  64:                     </table>
  65:                 </td>
  66:                 <td class="regright">
  67:                 </td>
  68:             </tr>
  69:         </table>
  70:         </div>        
  71:           <br />
  72:         <br />
  73:     </form>
  74: </asp:Content>

As you can see I am not modify any actions on the form or any names on the control just customizing the div’s classes and table classes to make them look better and consistent with our application. Once that is done go ahead and run your application. From the index page, click on registration link available in the login box. Your registration page should look something like below.

After modifying look and feel we also want to modify the registration method to incorporate custom registration. For this go to AccountController.cs file. Navigate to the registration method and change it to look something like below.

 

   1: public ActionResult Register(string username, string email, string password, string confirmPassword)
   2:         {
   3:  
   4:             ViewData["Title"] = "Register";
   5:             ViewData["PasswordLength"] = Provider.MinRequiredPasswordLength;
   6:  
   7:             // Non-POST requests should just display the Register form 
   8:             if (Request.HttpMethod != "POST")
   9:             {
  10:                 return View();
  11:             }
  12:  
  13:             // Basic parameter validation
  14:             List<string> errors = new List<string>();
  15:  
  16:             if (String.IsNullOrEmpty(username))
  17:             {
  18:                 errors.Add("You must specify a username.");
  19:             }
  20:             if (String.IsNullOrEmpty(email))
  21:             {
  22:                 errors.Add("You must specify an email address.");
  23:             }
  24:             if (password == null || password.Length < Provider.MinRequiredPasswordLength)
  25:             {
  26:                 errors.Add(String.Format(CultureInfo.InvariantCulture,
  27:                          "You must specify a password of {0} or more characters.",
  28:                          Provider.MinRequiredPasswordLength));
  29:             }
  30:             if (!String.Equals(password, confirmPassword, StringComparison.Ordinal))
  31:             {
  32:                 errors.Add("The password and confirmation do not match.");
  33:             }
  34:  
  35:             if (errors.Count == 0)
  36:             {
  37: LinksMVC.Models.LinkManagerDataContext lm = new LinksMVC.Models.LinkManagerDataContext();
  38:  
  39:                 try
  40:                 {
  41:                 lm.fm_RegisterUser(username, password, email, "", "", "", 2);
  42:                 }
  43:                 catch (Exception ex)
  44:                 {
  45:                  errors.Add("Can not create user at Try Later.");
  46:                  //errors.Add(ex.Message.ToString());
  47:                 }
  48:                
  49:             // If we got this far, something failed, redisplay form
  50:             ViewData["errors"] = errors;
  51:             ViewData["username"] = username;
  52:             ViewData["email"] = email;
  53:             return View();
  54:         }

Msot of the code is the validation of the user input which I am going to leave alone and directly modify the registration method which is below.

 

   1: if (errors.Count == 0)
   2:             {
   3: LinksMVC.Models.LinkManagerDataContext lm = new LinksMVC.Models.LinkManagerDataContext();
   4:                 try
   5:                 {
   6:                 lm.fm_RegisterUser(username, password, email, "", "", "", 2);
   7:                 }
   8:                 catch (Exception ex)
   9:                 {
  10:                  errors.Add("Can not create user at Try Later.");
  11:                  //errors.Add(ex.Message.ToString());
  12:                 }

I will check for any errors if/any so far. If now I will call a stored proceudre I have created inside SQL Server Database and mapped it to the Data Context file in our project. Finally I am passing all the parameters inside this function and checking if there are any erros. If not I will return the view without errors else we will put errors and return view where we are handling errors on registration view page.

 

Now let’s go to our HomeController.cs file and modify your Index method. Let’s try to understand what we modified in this code.

 

   1: if (errors.Count == 0)
   2:             {
   3: LinksMVC.Models.LinkManagerDataContext lm = new LinksMVC.Models.LinkManagerDataContext();
   4:                 try
   5:                 {
   6:                 lm.fm_RegisterUser(username, password, email, "", "", "", 2);
   7:                 }
   8:                 catch (Exception ex)
   9:                 {
  10:                  errors.Add("Can not create user at Try Later.");
  11:                  //errors.Add(ex.Message.ToString());
  12:                 }
  13: public ActionResult Index()
  14:         {
  15:             ViewData["Title"] = "Home Page";
  16:  
  17:             if (User.Identity.IsAuthenticated)
  18:             {
  19:                 string username = User.Identity.Name.ToString();
  20: LinksMVC.Models.LinkManagerDataContext lm = new LinksMVC.Models.LinkManagerDataContext();
  21:                 var uid = from m in lm.lnkUsers
  22:                                  where m.Username == username
  23:                                  select m.UserId;
  24:  
  25:                 var categories = from cat in lm.lnkCategories
  26:                                  where cat.UserId == uid.ToList().First()
  27:                                  select cat.CategoryName;
  28:  
  29:                 ViewData["Categories"] = categories.ToList();
  30:                 ViewData["Message"] = "Welcome to ASP.NET MVC!"+ User.Identity.Name.ToString();
  31:             }
  32:             else
  33:             {
  34:                 ViewData["Message"] = "Welcome to ASP.NET MVC!";
  35:                 ViewData["Categories"] = null;
  36:             }
  37:             
  38:             return View();
  39:         }

The first thing I am doing is checking if the user is logged in to the system or not. If he/she is not logged in to the system we will not show anything.  If you want you can show some text or some events happening on your site or some latest updates from the users and their public links. [We will implement this functionality later in this series. At that time we will modify this page to show only public data when he/she is not logged in. For now I have just set the categories to null if the user is not logged in. The interesting scenario is while the user is logged in. In this case we will have to fetch his/her categories he/she has created for their favorite manger. For that purpose I am writing two LINQ statements as show in the code above. Those who don’t know how I got this datacontext ready for my application please refer to this article.

MVC Preview 4 – Custom Login

I assume that you now have idea how I managed to get this datacontext for the application. Let’s understand the first query.

if (User.Identity.IsAuthenticated)

            {

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

LinksMVC.Models.LinkManagerDataContext lm = new LinksMVC.Models.LinkManagerDataContext();

                var uid = from m in lm.lnkUsers

                                 where m.Username == username

                                 select m.UserId;

 

 

If the user is authenticated first thing I will have to do is to retrieve the username who is logged in to the system. I did that by using User.Identity.Name. Then I am writing my first query to fetch the userid of the user who is logged. Why would I need that? because in my database the table lnkCategories is containing userid as a foreign key to relate categories to users. Ok so now with that query I have user id stored in the var uid. The next for me is to bring the categories this users has created for managing his/her favourites. Take a look at the query below.

 

var categories = from cat in lm.lnkCategories

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

                                 select cat.CategoryName;

Here I am writing LINQ statement to fetch CategoryName from the lnkCategories tbale where user id is uid.ToList().First().This will bering all the categories users has created. Finally I am storing this result to foreward it to view page by

ViewData["Categories"] = categories.ToList();

 

And next I will return this view to the actual view page. Let’s see what we have to write in our actual View page which is Index page to handle in coming input and display it to users. This code is pretty simple as compare to the code we look before in size but tricky as well. Because what you are doing is displaying tabulare dat without gridview that we all were used to do before.

   1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true"
   2:     CodeBehind="Index.aspx.cs" Inherits="LinksMVC.Views.Home.Index" %>
   3:  
   4: <%@ Import Namespace="LinksMVC" %>
   5: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
   6:     <br />
   7:     <br />
   8:     <%
   1:  
   2:         IList<string> categories = ViewData["Categories"] as IList<string>;
   3:         if (categories != null)
   4:         {
   5:     
%>
   9:     <ul class="categories">
  10:         <%
   1:  foreach (string category in categories)
   2:            { 
%>
  11:         <li>
  12:             <%
   1: = Html.Encode(category)
%></li>
  13:         <%
   1:  } 
%>
  14:     </ul>
  15:     <%
   1:  
   2:         }
   3:     
%>
  16: </asp:Content>

The first thing I am doing is checking if the if (categories != null). This is when the users is not registered we don’t want our application to break and show error message. If it is not null it means the usre is registered and we have to show them their favourite links. I am creating simple foreach look to achieve this.

 

Inside this foreach loop I am selecting eveyr single category inside that and showing in in the <li> HTML tag as I don’t want them to come one after another in horiznotal direction. Now go ahead and run the application. Don’t forget to check your index page when you are not logged in. Now log in and you will be redirected to the index page again where you should see some screen like below.

As you can see now I will little welcome message as well as the categories being created by user key. So that was easy right ? So far we have achieved the stage where we can go ahead and develop full fledged applicatoin using LINQ and MVC Preview 4. In the future series we will try to conver these categories to actions and retrive links stored for every category.

We will also created functionalities for Creating/Editing/Deleting categoroies as well Creating/Editing/Deleting links inside different categoreis. Go ahead and play around with this application. Soruce code is attached for the application along with the datbase script.

Thanks

 


Keywords :
Tags :
Rate This Article :

Comments :
Write a Comment / Question / Feedback ...


User Login
Username :
Password :
Register Login

Forgot Password


Related Articles