October 31, 2012

In this post, I will show how to create an asp.net MVC 4.0 project using Visual Studio 10 SP1. The built in templates in Visual Studio makes it easy to start creating the application. In the screenshot below, I have opened Visual Studio, and creating a new MVC 4.0 project using .NET 4.0 . I have called the solution MvcDemo.

1

After clicking OK, I will choose Internet Application as the template and Razor as the view engine and also create unit test project.

2

Visual Studio creates a working application once the OK button is hit. Folders and files have been created by default for Controllers, Models, Views, Filters, Scripts, Contents, etc. The screen shot below shows the full structure.

3

The application can now be started in Debug mode by hitting F5.

4

The application, by default, shows some informative messages. It’s important to note that the data for this page is obtained from Index.cshtml View which is under the Home sub-folder of View folder. The View contains mostly static content and dynamically obtains some information referred ViewBag.Message and ViewBag.Title property as shown below.

5

The value of ViewBag.Title property is set in the first couple of lines within the View. The ViewBag.Message property is set within the Index() method of HomeController class which is located within the Controller directory.

HomeController
  1. namespace MvcDemo.Controllers
  2. {
  3.     public class HomeController : Controller
  4.     {
  5.         public ActionResult Index()
  6.         {
  7.             ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
  8.  
  9.             return View();
  10.         }

October 27, 2012

The built in ModalPopupExtender of Ajax Control Tookit makes it very easy to implement modal windows in asp.net. The extender have options for the location of the popup, drag feature, drag handle and option for styling the background and animating the popup. In this post, I will setup an animated Modal Popup with drag feature.

The code for the ModalPopupExtender is below.

Modal Popup Extender
  1. <asp:Button ID="Button1" runat="server" Text="Modal" />
  2. <cc:ModalPopupExtender ID="ModalPopupExtender1" runat="server" CancelControlID="BCancel" Drag="true" OkControlID="BOk" PopupControlID="PModal" PopupDragHandleControlID="PHandle" TargetControlID="Button1" BackgroundCssClass="bModal">
  3.     <Animations>
  4.         <OnShown>
  5.             <FadeIn Duration="0.8" Fps="40" />
  6.         </OnShown>
  7.         <OnHiding>
  8.             <FadeOut Duration="0.8" Fps="40" />
  9.         </OnHiding>
  10.     </Animations>
  11.  
  12. </cc:ModalPopupExtender>

The PopupControlID is the id of the control that will be displayed when the button (TargetControlID) is clicked. The Drag property determines if the popup can be dragged and PopupDragHandleControlID property determines the control that can be dragged. If PopupDragHandleControlID is not set, the popup can be dragged from anywhere within the popup. The Animation section determines the animations properties of the popup. In this example, I have set 0.8 seconds for fade in and dade out.

The code for the popup control (an asp Panel control in my example) is below.

Popup Panel
  1. <asp:Panel ID="PModal" runat="server">
  2.     <asp:Panel ID="PHandle" runat="server" CssClass="modalHandle">Popup Title
  3.     <span style="float:right;"><asp:Button ID="BCancel" runat="server" Text="X" CssClass="closeModal" />    </span>
  4.     <br />
  5.     </asp:Panel>
  6.  
  7.     <div class="modalContent">some content some content some content<br /> some content some content some content <br /><br />
  8.         <asp:Button ID="BOk" runat="server" Text="Ok" />
  9.             
  10.     </div>
  11. </asp:Panel>

As can be seen, there is a nested Panel with id PHandle with a css class associated with it. This Panel will be used for dragging the control. It also contains the Cancel Button for closing the window. There is another nested div element that contains the contents for the popup. Then, there is the Ok button, which when clicked can do a postback and close the popup.

I have added css to different elements including the popup, background when popup is shown, drag handle and close button. The css code is below.

CSS
  1. <style type="text/css">
  2. .bModal { background-color:#eee; opacity:0.6; filter:alpha(opacity=60);}
  3. .modalContent { background-color:#fff; border:1px solid #ccc; width:400px; padding:2px 4px;}
  4. .modalHandle { background-color:#ccc; cursor:move; height:18px; padding:2px 4px; font-weight:bold;}
  5. .closeModal { background-color:#ccc; color:#fff; font-weight:bold; border:0;}
  6. </style>

In my example, the popup has been activated when the Button is clicked. The popup could also have been shown from the server side - for example, from Page Load event like below.

Page Load event
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     
  4.     ModalPopupExtender1.Show();
  5. }

Please note, if the popup doesn't need a button to be triggered, then the button os some other control still need to added on the page and can be hidden by using css like below. If the TargetControlId is left blank, the popup will not work.

Screen shot for the popup is below.

popup

October 24, 2012

GridView can be used to display tabular data. Sometimes, instead of paging data, it might be user friendly to display all data in a scrollable format.

It's quite easy to implement this using CSS. In the example below, I have got a div element with a GridView in it and have applied styles to the div to allow scrolling. 

GridView
  1. <div style="height:200px; overflow:scroll;">
  2.     <asp:GridView ID="Gv2" runat="server" AutoGenerateColumns="true"
  3.             DataKeyNames="Uid" DataSourceID="EntityDataSource2">
  4.     </asp:GridView>
  5.         
  6.     <asp:EntityDataSource ID="EntityDataSource2" runat="server"
  7.         ConnectionString="name=ProductsEntities"
  8.         DefaultContainerName="ProductsEntities" EnableFlattening="False"
  9.         EntitySetName="Products">
  10.     </asp:EntityDataSource>    
  11. </div>

October 23, 2012

GridView offers ways to customise row and alternate rows' properties. Sometimes it might be useful to highlight certain rows based on the data it contains. For example, we might have a gridview for products and we might want to highlight rows whose products have price less than 100, etc. In this example, I will use entity data source to bind the gridview and based on the price value, highlight the background colour using the RowCreated event.

Here is the code for it.

GridView Markup
  1. <asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False"
  2.     DataSourceID="EntityDataSource1" OnRowCreated="RowCreated" DataKeyNames="Uid">
  3.     <Columns>            
  4.         <asp:BoundField DataField="ProductId" HeaderText="ProductId"
  5.             SortExpression="ProductId" />
  6.         <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />            
  7.     </Columns>
  8. </asp:GridView>
  9.  
  10.  
  11. <asp:EntityDataSource ID="EntityDataSource1" runat="server"
  12.     ConnectionString="name=ProductsEntities"
  13.     DefaultContainerName="ProductsEntities" EnableFlattening="False"
  14.     EntitySetName="PriceHistories">
  15. </asp:EntityDataSource>
Row Created Event
  1. protected void RowCreated(object sender, GridViewRowEventArgs e)
  2. {
  3.     if (e.Row.DataItem != null)
  4.     {
  5.         double price = (double)((PriceHistory)e.Row.DataItem).Price.Value;
  6.  
  7.         if (price > 100)
  8.             e.Row.BackColor = System.Drawing.Color.FromArgb(200, 200, 100);
  9.     }
  10. }

You might be wondering what PriceHistory class is - this class is defined within the entity model.

GridView is a data control that supports displaying data in a grid layout which is essentially an html table. It has built in support for updating, deleting, sorting and paging data, however, its lack of flexible layout makes it not the best option. For example, if we want to display the result of a search, we don't necessarily want to display the data in a tabular format.

This is where ListView comes in - it provides a highly customisable and flexible layout. ListViwe can contain any html elements in it like div, p, li, table and any other server side controls. Like GridView, it supports updating, deleting and sorting data. It also supports inserting and data grouping. Paging is also supported via DataPager control.

The following is an example of the how to declare and use GridView and ListView.

GridView
  1. <asp:GridView ID="gv" runat="server" AllowPaging="True" AllowSorting="True"
  2.     CellPadding="4" ForeColor="#333333" GridLines="None" EmptyDataText="Data not found">
  3.     <AlternatingRowStyle BackColor="White" />
  4.     <Columns>
  5.         <asp:CommandField ShowEditButton="True" />
  6.         <asp:CommandField ShowSelectButton="True" />
  7.         <asp:CommandField ShowDeleteButton="True" />
  8.     </Columns>
  9.     <EditRowStyle BackColor="#2461BF" />
  10.     <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  11.     <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
  12.     <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
  13.     <RowStyle BackColor="#EFF3FB" />
  14.     <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
  15.     <SortedAscendingCellStyle BackColor="#F5F7FB" />
  16.     <SortedAscendingHeaderStyle BackColor="#6D95E1" />
  17.     <SortedDescendingCellStyle BackColor="#E9EBEF" />
  18.     <SortedDescendingHeaderStyle BackColor="#4870BE" />
  19. </asp:GridView>

 

ListView
  1. <asp:ListView ID="LView" runat="server" GroupItemCount="3" GroupPlaceholderID="groupPlaceHolder">
  2.     <LayoutTemplate>
  3.         <div class="layout"><asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder></div>
  4.  
  5.         <asp:DataPager runat="server" ID="ColDataPager" PageSize="10" DataKeyNames="ID"
  6.             OnItemInserted="LView_Insert" InsertItemPosition="LastItem">
  7.           <Fields>
  8.             <asp:NextPreviousPagerField
  9.               ShowFirstPageButton="true" ShowLastPageButton="true"
  10.               FirstPageText="First " LastPageText=" Last"
  11.               NextPageText=" Next " PreviousPageText=" Prev " />
  12.           </Fields>
  13.         </asp:DataPager>
  14.     </LayoutTemplate>
  15.  
  16.     <GroupTemplate>
  17.         <ul><li>
  18.             <asp:PlaceHolder runat="server" ID="groupPlaceHolder"></asp:PlaceHolder>
  19.         </li></ul>
  20.     </GroupTemplate>
  21.  
  22.     <ItemTemplate>
  23.         <span class="l1_n"><%#Eval("column1") %></span>
  24.     </ItemTemplate>
  25.  
  26.     <AlternatingItemTemplate>
  27.         <span class="l1_alt"><%#Eval("column1") %></span>
  28.     </AlternatingItemTemplate>
  29.  
  30.     <ItemSeparatorTemplate>
  31.         <hr />
  32.     </ItemSeparatorTemplate>
  33.  
  34.  
  35.     <InsertItemTemplate>
  36.         <asp:Label runat="server" ID="LColumn1" AssociatedControlID="TBColumn1" Text="Column1"/>
  37.         <asp:TextBox ID="TBColumn1" runat="server" Text='<%#Bind("column1") %>' /><br />
  38.         <asp:LinkButton ID="LbInsert" runat="server" CommandName="Insert" Text="Insert" />
  39.     </InsertItemTemplate>
  40.  
  41. </asp:ListView>

As you can see, it is lot easier to declare and use the GridView compare to ListView, however, the resultant view is more user friendly with ListView as long as you don't enter weird styles for the controls.

Reference: Shahed Kazi at AspNetify.com