Introduction to ASP.NET MVC using C#

Getting Started
Start by running Visual Studio 2010  and select New Project from the Start page.



Visual Studio 2010 - Start Page
Visual Studio 2010 – Start Page
Creating Your First Application
You can create ASP.NET MVC Web applications using either Visual Basic or Visual C# as the programming language. Select Visual C# on the left and then select ASP.NET MVC 2 Web Application. Name your project “MvcBook” and then click OK.
ASP.NET MVC 2 Web Application
ASP.NET MVC 2 Web Application

This creates a simple “Hello World!” MVC project

MVC Home Controller Page
MVC Home Controller Page

Click Debug menu, select Start Debugging or Press F5

Visual Studio launches a browser and opens the application’s home page.
MVC 2 Application Home Page
MVC 2 Application Home Page

 

ASP.NET MVC Design

ASP.NET MVC Design



ASP.NET MVC Design

ASP.NET MVC Design



ASP.NET MVC Design pattern derives from MVC design pattern i.e. Model View Controller design pattern. It seperates the responsibilities.C in MVC is for Controller. Controller is component which acts as target to external stimulus. Controller then responds to stimulus by calling Model to fetch data and then View to display data in UI .

ASP.NET MVC Design pattern seperates the behaviour i.e. Data , UI and Event.

Microsoft Web Platform Installer

Microsoft Web Platform Installer

Microsoft Web Platform Installer (Web PI) is a free tool that makes getting the latest components of the Microsoft Web Platform, including Internet Information Services (IIS), SQL Server Express, .NET Framework and Visual Web Developer easy. The Web PI also makes it easy to install and run the most popular free web applications for blogging, content management and more with the built-in Windows Web Application Gallery.

Download the Microsoft Web Platform Installer

http://www.microsoft.com/web/downloads/platform.aspx

Setting Menu options Dynamically based on Role in ASP.NET using LINQ

Setting Menu options Dynamically based on Role in ASP.NET using LINQ

Step 1. Add Menu control to aspx or master page.

<asp:Menu ID=”menuRoleBased” runat=”server” Font-Names=”Verdana” ForeColor=”WhiteSmoke” Orientation=”Horizontal”
                            BorderColor=”#FFCC99″ BorderWidth=”0px” Width=”20%” Font-Bold=”False” Font-Size=”Smaller”>
                            <StaticMenuStyle BorderWidth=”1″ BackColor=”#FFCC99″ BorderColor=”White” BorderStyle=”Solid” />
                            <StaticSelectedStyle Font-Names=”Verdana” BackColor=”#415779″ ForeColor=”white” Height=”25px” />
                            <StaticMenuItemStyle CssClass=”menuHoverStyle” Font-Names=”Verdana” HorizontalPadding=”4px”
                                BorderColor=”White” BorderStyle=”Solid” BorderWidth=”1px” ForeColor=”Black” Height=”25px” />
                            <StaticHoverStyle CssClass=”menuOrangeStyle” Height=”25px” Font-Names=”Verdana” ForeColor=”Black” />
                            <DynamicHoverStyle CssClass=”menuOrangeStyle” Height=”25px” Font-Names=”Verdana”
                                ForeColor=”Black” />
                            <DynamicMenuStyle BorderStyle=”Solid” BorderColor=”white” BorderWidth=”1″ Height=”25px”
                                Font-Names=”Verdana” ForeColor=”White” BackColor=”#FFCC99″ />
                            <DynamicSelectedStyle Height=”25px” Font-Names=”Verdana” ForeColor=”White” BackColor=”#001B36″ />
                            <DynamicMenuItemStyle BorderStyle=”Solid” BorderWidth=”1px” BorderColor=”white” Height=”25px”
                                Font-Names=”Verdana” ForeColor=”white” BackColor=”#FFCC99″ HorizontalPadding=”3px” />
                            <DataBindings>
                                <asp:MenuItemBinding DataMember=”Menu” TextField=”title” ValueField=”description”
                                    NavigateUrlField=”url” />
                                <asp:MenuItemBinding DataMember=”SubMenu” NavigateUrlField=”url” TextField=”title”
                                    ValueField=”description” />
                            </DataBindings>
 </asp:Menu>

Step 2 : Add a xml containing Menu  and Submenu Name , Url and Role. Add a xml file to your project and add below xml content to it.

Xml below has two menus – Request Leave menu for Employee and Approve Leave menu for Manager

<?xml version=”1.0″ encoding=”utf-8″ ?>
<RootMenu>
  <Menu url=”” title=”Request” description=”Request” Role=”Employee” MenuOrder=”0″>
    <SubMenu url=”RequestLeave.aspx”  title=”Request Leave” description=”” />
  </Menu>
  <Menu  url=””  title=”Approve” description=”” Role=”Manager” MenuOrder=”1″>
    <SubMenu url=”ApproveLeave.aspx”  title=”Approve Leave” description=”” />
  </Menu>
 </RootMenu>

Step 3: Write a method to return roles of logged in user. In this example, I will create a GetRole method and populate to set Role array to Employee.

 public String[] GetRole()
    {
        return  new String[]{“Employee”};
    }

Step 4 : Write a method to get Menu xml string dynamically based on role.

public String GetMenu()
    {
        string strMenu = string.Empty;
        string[] loggedUserRole= GetRole();
        DataSet dsMenu = new DataSet();
        string strPath = @”D:MenuMenuRole.xml”;
       
        XDocument xmlDoc = XDocument.Load(strPath);

        List<XElement> roleMenu = new List<XElement>();
        var test = from c in xmlDoc.Descendants(“Menu”)
                   join r in loggedUserRole on c.Attribute(“Role”).Value equals r
                   orderby c.Attribute(“MenuOrder”).Value ascending
                   select c;

        foreach (var p in test)
            strMenu = strMenu + p.ToString();
        strMenu = “<RootMenu>” + strMenu + @”</RootMenu>”;
        return strMenu;
    }

Step 5 : Add xmlDataSource control to aspx or masterpage

<asp:XmlDataSource ID=”srcXMLMPA” runat=”server” XPath=”RootMenu/Menu” EnableCaching=”false”>
    </asp:XmlDataSource>

Step 6 : Add the code to bind dynamically created Role based menu xml string to Menu control

srcXMLMPA.Data = GetMenu();
menuRoleBased.DataSource = srcXMLMPA;
menuRoleBased.DataBind();

Now run the web application to see the result . Since Role array was populated with Employee role therefore only Request Menu will be show . See the result below :

EmployeeMenu
Employee Menu

Now change GetRole method to return Employee and Manager role and run the application to see the difference :

ManagerMenu
Manager Menu

ASP.NET , C# – Configuring to use XML to display error and validation message

ASP.NET , C# – Configuring to use XML to display error and validation message

Step 1 – Add XML file to store error and validation message.
              Below is sample of ErrorMessage.xml :
<?xml version=1.0 encoding=utf-8 ?>
<appSettings>
<add key=NoMatchingRecord value=No Matching Records Found/>
<appSettings>                  

Below is sample of ValidationMessage.xml :

<?xml version=”1.0″ encoding=”utf-8″ ?>
<appSettings>

 <add key=”EndDateGreaterthanStartDate” value=”End Date should be greater than Start Date”/>
</appSettings>

If more error or validation message need to be added then add it to ErrorMessage.xml or ValidationMessage.xml with key and value pair. Also , make sure key is unique and not repeated in XML file. You can also add more XML files if needed

Step 2 – Add below key in appSettings section of Web.config file
<appSettings>
  <add key=”ErrorMessage” value=”D:ConfigErrorMessage.xml”></add>
  <add key=”ValidationMessage” value=”D:ConfigValidationMessage.xml”></add>
 </appSettings>

Above keys are added which contains path of XML file as  key value

Step 3 – Add a Class file and name it to CustomMessage.cs . Add below code in Custom Message.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
////// <summary> Summary description for CustomMessage/// </summary>
public class CustomMessage{
System.Xml.XmlDocument doc;

{
}
public CustomMessage(String FileName)
{
doc = new XmlDocument();
doc.Load(FileName);
}

/// <summary>/// To get value from XML file at specified location./// </summary>/// <param name=”TagName”></param>/// <returns></returns>

public string GetMessageValue(string TagName)
    {
        string ConstString = string.Empty;
        try
        {
            //Get Connection path from XML file

            XmlNodeList elemList = doc.GetElementsByTagName(“add”);
            for (int i = 0; i < elemList.Count; i++)
            {
                string KeyName = elemList[i].Attributes[“key”].Value;
                if (KeyName == TagName)
                {
                    ConstString = elemList[i].Attributes[“value”].Value;
                }
            }
        }
        catch (Exception ex)
        {
        }
        return ConstString;
    }

}

CustomMessage class contains a public constructor which accepts FileName as input paramter and load the XML file into XMLDocument.

CustomMessage class also contains a method GetMessageValue which takes key as input parameter and returns value of key.

Step 4 – Final step is to consume the CustomMessage class to display appropriate message. Below is code in calling aspx or cs file :

string errorFile = ConfigurationManager.AppSettings.Get(“ErrorMessage”).ToString();
CustomMessage objCustomMessage = new CustomMessage(errorFile);

this.lblError.Text = objCustomMessage.GetMessageValue(“NoMatchingRecord”);

Line 1 is used to get path of ErrorMessage.xml
Line 2 is used to call Custom message class constructor to load XML file into XMLDocument
Line 3 is used to get value of error message key by passing key to CustomMessage method GetMessageValue

string validationFile = ConfigurationManager.AppSettings.Get(“ValidationMessage”).ToString();
CustomMessage objCustomMessage = new CustomMessage(validationFile);this.lblValidation.Text = objCustomMessage.GetMessageValue(“EndDateGreaterthanStartDate”);  

 Line 1 is used to get path of ValidationMessage.xml
 Line 2 is used to call Custom message class constructor to load XML file into XMLDocument
 Line 3 is used to get value of validation message key by passing key to CustomMessage method GetMessageValue

AJAX Client Side Event Life Cycle

AJAX Client Side Event Life Cycle

1.      Page Request

2.      Init

3.      Load

·         initializeRequest

·         beignRequest

·         pageLoading

·         pageLoaded

4.         Load

·          endRequest

5.      unLoad

 Interview Question links :

AJAX UpdateProgress control : Avoid multiple updates to Update Panel

This tutorial will demonstrate how UpdateProgress control can be used to avoid multiple updates to Update Panle while one update request is in progress.

To delay the refresh of data , Thread.Sleep of around 18000 milli seconds is introduced.

Steps to be followed are below :

1. Add a Script Manger control

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”></asp:ScriptManager>

 2. Add a AJAX Update Panel control . With in UpdatePanel control , add a Label and Button control

<asp:UpdatePanel ID=”updPanel” runat=”server” UpdateMode=”Conditional”><ContentTemplate><asp:Label runat=”server” id=”lblDateTime” ></asp:Label>

</<asp:Button runat=”server” id=”btnUpdateDateTime” text=”Update Date Time” onclick=”btnUpdateDateTime_Click” />ContentTemplate></asp:UpdatePanel>

 3. Add a AJAX UpdateProgess control and Set to AssociatedUpdatePanelID to UpdatePanel control id.

<asp:UpdateProgress ID=”updProgess” runat=”server” AssociatedUpdatePanelID=”updPanel” ><ProgressTemplate>Please Wait.Refreshing Data …<br /><span id=”msgSpan”></span></ProgressTemplate></asp:UpdateProgress> 

4. Add a script block below Script Manager Control  :

<script type=”text/javascript”>
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CheckStatus);
function CheckStatus(sender,args)

{
var par = Sys.WebForms.PageRequestManager.getInstance();
              if ( par.get_isInAsyncPostBack())
               {
                      $get(“msgSpan”).innerHTML = ” Still processing previous request..”;
                       args.set_cancel(true);
               }
              else
             {
                     $get(“msgSpan”).innerHTML = “”

             }
}
</script>

5. Add Update Button click event


protected void btnUpdateDateTime_Click(object sender, EventArgs e)

{
Thread.Sleep(10000);
lblDateTime.Text = DateTime.Now.ToString();

}

In the client script CheckStatus , we get instance of web form from PageRequestManager. Then we check where there is any Async Post Back is in progress using the method get_isInAsyncPostback(). If yes, then message is set to Still processing previous request. If no then message is set to blank.

Demo of what we have acheieved using above code

Page on initial load :

Page on click of Update Date Time button

Page on click of Update Date Time button avoid multiple updates
Hope you enjoyed this tutorial. For feedback , please leave your comments. Happy Coding


What is ScriptManager ?

 ScriptManager

ScriptManager control on a page  is used to enable the Microsoft Ajax features of ASP.NET:
  • Client-script functionality of the Microsoft Ajax Library,

  • Partial-page rendering, which enables portions of page to be independently refreshed without a postback.  UpdatePanel, UpdateProgress, and Timer controls require a ScriptManager control in order to support partial-page rendering.

  • JavaScript proxy classes for Web services, which enable you to use client script to access Web services and specially marked methods in ASP.NET pages. It does this by exposing the Web services and page methods as strongly typed objects.

  • JavaScript classes to access ASP.NET authentication, profile, and roles application services.