Where to define AutoEventWireup attribute in ASP.NET
•
|
The Machine.config file
|
•
|
The Web.config file
|
•
|
Individual Web Forms (.aspx files)
|
•
|
Web User Controls (.ascx files)
|
•
|
The Machine.config file
|
•
|
The Web.config file
|
•
|
Individual Web Forms (.aspx files)
|
•
|
Web User Controls (.ascx files)
|
When you set the value of the AutoEventWireup attribute to true, the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.
![]() |
Visual Studio 2010 – Start Page |
![]() |
ASP.NET MVC 2 Web Application |
![]() |
MVC Home Controller Page |
![]() |
MVC 2 Application Home Page |
|
ASP.NET MVC Design |
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 :
![]() |
Employee Menu |
Now change GetRole method to return Employee and Manager role and run the application to see the difference :
![]() |
Manager Menu |
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
To delay the refresh of data , Thread.Sleep of around 18000 milli seconds is introduced.
Steps to be followed are below :
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”></asp:ScriptManager>
<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>
<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