Search Results

Search found 1705 results on 69 pages for 'runat'.

Page 9/69 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • add_shown & add_hiding ModalPopupExtender Events

    - by Yousef_Jadallah
        In this topic, I’ll discuss the Client events we usually need while using ModalPopupExtender. The add_shown fires when the ModalPopupExtender had shown and add_hiding fires when the user cancels it by CancelControlID,note that it fires before hiding the modal. They are useful in many cases, for example may you need to set focus to specific Textbox when the user display the modal, or if you need to reset the controls values inside the Modal after it has been hidden. To declare Client event either in pageLoad javascript function or you can attach the function by Sys.Application.add_load like this: Sys.Application.add_load(modalInit); function modalInit() { var modalPopup = $find('mpeID'); modalPopup.add_hiding(onHiding); } function onHiding(sender, args) { } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   I’ll use the first way in the current example. So lets start with the illustration:   1- In this example am using simple panel which contain UserName and Password Textboxes besides submit and cancel buttons, this Panel will be used as PopupControlID in the ModalPopupExtender : <asp:Panel ID="panModal" runat="server" Height="180px" Width="300px" style="display:none" CssClass="ModalWindow"> <table width="100%" > <tr> <td> User Name </td> <td> <asp:TextBox ID="txtName" runat="server"></asp:TextBox> </td> </tr> <tr> <td> Password </td> <td> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox> </td> </tr> </table> <br /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> <asp:Button ID="btnCancel" runat="server" Text="Cancel" /> </asp:Panel>   You can use this simple style for the Panel : <style type="text/css"> .ModalWindow { border: solid; border-width:3px; background:#f0f0f0; } </style> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   2- Create the view button (TargetControlID) as you know this contain the ID of the element that activates the modal popup: <asp:Button ID="btnView" runat="server" Text="View" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   3-Add the ModalPopupExtender ,moreover don’t forget to add the ScriptManager: <asp:ScriptManager ID="ScriptManager1" runat="server"/> <cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnView" PopupControlID="panModal" CancelControlID="btnCancel"/> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }     4-In the pageLoad javascript function inside add_shown event set the focus on the txtName , and inside add_hiding reset the two Textboxes. <script language="javascript" type="text/javascript"> function pageLoad() { $find('ModalPopupExtender1').add_shown(function() { alert('add_shown event fires'); $get('<%=txtName.ClientID%>').focus();   });   $find('ModalPopupExtender1').add_hiding(function() { alert('add_hiding event fires'); $get('<%=txtName.ClientID%>').value = ""; $get('<%=txtPassword.ClientID%>').value = "";   }); }   </script> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   I’ve added the two alerts just to let you show when the event fires.   Hope this simple example show you the benefit and how to use these events.

    Read the article

  • Securing ASP.Net Pages - Forms Authentication - C# and .Net 4

    - by SAMIR BHOGAYTA
    ASP.Net has a built-in feature named Forms Authentication that allows a developer to easily secure certain areas of a web site. In this post I'm going to build a simple authentication sample using C# and ASP.Net 4.0 (still in beta as of the posting date). Security settings with ASP.Net is configured from within the web.config file. This is a standard ASCII file, with an XML format, that is located in the root of your web application. Here is a sample web.config file: configuration system.web authenticationmode="Forms" formsname="TestAuthCookie"loginUrl="login.aspx"timeout="30" credentialspasswordFormat="Clear" username="user1"password="pass1"/ username="user2"password="pass2"/ authorization denyusers="?"/ compilationtargetFramework="4.0"/ pagescontrolRenderingCompatibilityVersion="3.5"clientIDMode="AutoID"/ Here is the complete source of the sample login.aspx page: div Username: asp:TextBox ID="txtUsername" runat="server":TextBox Password: asp:TextBox ID="txtPassword" runat="server":TextBox asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Login" / asp:Label ID="lblStatus" runat="server" Text="Please login":Label /div And here is the complete source of the login.aspx.cs file: using System; using System.Web.UI.WebControls; using System.Web.Security; public partial class Default3 : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text)) { lblStatus.Text = ("Welcome " + txtUsername.Text); FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); } else { lblStatus.Text = "Invalid login!"; } } }

    Read the article

  • AJAX Control Toolkit - Globalization (Language)

    - by Guilherme Cardoso
    For those who use AjaxToolKit controls presenting a language-dependent data (the CalendarExternder with the names of the months and weeks, for example) you can change the language to be presented in a simple way. In Web.Config let's define the primary culture as follows: < system . web > <System. Web> < globalization uiCulture = "pt-pt" culture = "pt-pt" /> <Globalization UICulture = "en-us" culture = "en-us" /> ... ...  In this example I'm using Portuguese. To finish it is necessary to change our ScriptManager. Be it the ToolScriptManager AjaxToolKit or belonging to the ScriptManager's framework. NET, the properties as a vibrant and true are the EnableScriptGlobalization EnableScriptLocalization. < cc1 : ToolkitScriptManager ID = "ToolkitScriptManager1" runat = "server" EnableScriptGlobalization = "true" EnableScriptLocalization = "true" > <Cc1: ToolkitScriptManager ID = "ToolkitScriptManager1" runat = "server" EnableScriptGlobalization = "true" EnableScriptLocalization = "true"> </ cc1 : ToolkitScriptManager > </ Cc1: ToolkitScriptManager> or < asp : ScriptManager ID = "ScriptManager1" runat = "server" EnableScriptGlobalization = "true" EnableScriptLocalization = "true" > <Asp: ScriptManager ID = "ScriptManager1" runat = "server" EnableScriptGlobalization = "true" EnableScriptLocalization = "true"> </ asp : ScriptManager > </ Asp: ScriptManager>   Like hus we use the controls on AjaxToolKit, always using the Portuguese language. It is important that AjaxTookKit is updated to avoid shortages or errors in translation, though I have not updated by this error in the ModalPopup the latest version, and any controls that I have used are translated correctly.

    Read the article

  • How can I use AjaxFileUpLoad control? [migrated]

    - by DWHelper
    Now I'm using Visual Studio 2013 and I imported the AJAX Toolkit downloaded from Microsoft specific site successfully and drag and drop AjaxFileUpLoad control into my page form, and the generated codes are: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CSharp.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </ajaxToolkit:ToolkitScriptManager> <ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" MaximumNumberOfFiles="5" AllowedFileTypes="jpg"/> </div> </form> But the question is that I can run the page properly, click the black "Submit" button and upload a file, but it occurs an error……Why? This is the image attached:

    Read the article

  • Problems with Optimistic Concurrency through an ObjectDataSource and a GridView

    - by Bloodsplatter
    Hi I'm having a problem in an ASP .NET 2.0 Application. I have a GridView displaying data from an ObjectDataSource (connected to a BLL class which connects to a TabledAdapter (Typed Dataset using optimistic concurrency). The select (displaying the data) works just fine, however, when I update a row the GridView does pass the old values to the ObjectDataSource. <DataObjectMethod(DataObjectMethodType.Update, True)> _ Public Function UpdateOC(ByVal original_id As Integer, ByVal original_fotonummer As Integer, ByVal original_inhoud As String, ByVal original_postdatum As Date?, ByVal fotonummer As Integer, ByVal inhoud As String, ByVal postdatum As Date?) As Boolean Dim tweets As TwitpicOC.TweetsDataTable = adapterOC.GetTweetById(original_id) If tweets.Rows.Count = 0 Then Return False Dim row As TwitpicOC.TweetsRow = tweets(0) SmijtHetErIn(row, original_fotonummer, original_inhoud, original_postdatum) row.AcceptChanges() SmijtHetErIn(row, fotonummer, inhoud, postdatum) Return adapterOC.Update(row) = 1 End Function Public Sub SmijtHetErIn(ByVal row As TwitpicOC.TweetsRow, ByVal original_fotonummer As Integer, ByVal original_inhoud As String, ByVal original_postdatum As Date?) With row .fotonummer = original_fotonummer If String.IsNullOrEmpty(original_inhoud) Then .SetinhoudNull() Else .inhoud = original_inhoud If Not original_postdatum.HasValue Then .SetpostdatumNull() Else .postdatum = original_postdatum.Value End With End Sub And this is the part of the page: <div id='Overzicht' class='post'> <div class='title'> <h2> <a href='javascript:;'>Tweetsoverzicht</a></h2> <p> Overzicht</p> </div> <div class='entry'> <p> <asp:ObjectDataSource ID="odsGebruiker" runat="server" OldValuesParameterFormatString="" SelectMethod="GetAll" TypeName="TakeHomeWeb.BLL.GebruikersBLL"></asp:ObjectDataSource> <asp:ObjectDataSource ID="odsFoto" runat="server" SelectMethod="GetFotosByGebruiker" TypeName="TakeHomeWeb.BLL.FotosBLL"> <SelectParameters> <asp:ControlParameter ControlID="ddlGebruiker" DefaultValue="0" Name="userid" PropertyName="SelectedValue" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> <form id="form1" runat="server"> <asp:Label runat="server" AssociatedControlID="ddlGebruiker">Gebruiker:&nbsp;</asp:Label> <asp:DropDownList ID="ddlGebruiker" runat="server" AutoPostBack="True" DataSourceID="odsGebruiker" DataTextField="naam" DataValueField="userid" AppendDataBoundItems="True"> <asp:ListItem Text="Kies een gebruiker" Value="-1" /> </asp:DropDownList> <br /> <asp:Label runat="server" AssociatedControlID="ddlFoto">Foto:&nbsp;</asp:Label> <asp:DropDownList ID="ddlFoto" runat="server" AutoPostBack="True" DataSourceID="odsFoto" DataTextField="url" DataValueField="id" AppendDataBoundItems="True"> <asp:ListItem Value="-1">Kies een foto...</asp:ListItem> </asp:DropDownList> <br /> <div style="float: left"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="odsTweets"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" /> <asp:BoundField DataField="fotonummer" HeaderText="fotonummer" SortExpression="fotonummer" /> <asp:BoundField DataField="inhoud" HeaderText="inhoud" SortExpression="inhoud" /> <asp:BoundField DataField="postdatum" HeaderText="postdatum" SortExpression="postdatum" /> </Columns> </asp:GridView> <asp:ObjectDataSource ID="odsTweets" runat="server" ConflictDetection="CompareAllValues" DeleteMethod="DeleteOC" OldValuesParameterFormatString="original_{0}" SelectMethod="GetTweetsByFotoId" TypeName="TakeHomeWeb.BLL.TweetsOCBLL" UpdateMethod="UpdateOC"> <DeleteParameters> <asp:Parameter Name="original_id" Type="Int32" /> <asp:Parameter Name="original_fotonummer" Type="Int32" /> <asp:Parameter Name="original_inhoud" Type="String" /> <asp:Parameter Name="original_postdatum" Type="DateTime" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="original_id" Type="Int32" /> <asp:Parameter Name="original_fotonummer" Type="Int32" /> <asp:Parameter Name="original_inhoud" Type="String" /> <asp:Parameter Name="original_postdatum" Type="DateTime" /> <asp:Parameter Name="fotonummer" Type="Int32" /> <asp:Parameter Name="inhoud" Type="String" /> <asp:Parameter Name="postdatum" Type="DateTime" /> </UpdateParameters> <SelectParameters> <asp:ControlParameter ControlID="ddlFoto" Name="foto" PropertyName="SelectedValue" Type="Int32" /> </SelectParameters> </asp:ObjectDataSource> </div> </form> </p> </div> </div> I've got a feeling there's huge fail involved or something, but I've been staring at it for hours now and I just can't find it.

    Read the article

  • how to find datakeys in oncheckedchanged event ?

    - by subodh
    <asp:Panel ID="pnlFocusAreaPanel" runat="server" GroupingText="Focus Area" Width="800"> <table cellspacing="0" cellpadding="0" width="750"> <tr> <td> <asp:GridView ID="dgFocusAreaDetails" runat="server" Width="100%" CssClass="dgStyle" AutoGenerateColumns="False" BorderColor="Silver" BorderWidth="1px" CellPadding="0" ShowHeader="False" OnSelectedIndexChanged="dgFocusAreaDetails_SelectedIndexChanged" DataKeyNames="PK_ID"> <FooterStyle Font-Underline="True" HorizontalAlign="Center" VerticalAlign="Middle"> </FooterStyle> <Columns> <asp:TemplateField HeaderText="Focus Area" HeaderStyle-BackColor="Silver"> <ItemStyle Width="90%" /> <ItemTemplate> <asp:Label runat="server" ID="lblFocusArea" Text='<%# DataBinder.Eval(Container.DataItem, "FOCUS_AREA_NAME").ToString()%>'> </asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Is Current Valid" HeaderStyle-BackColor="Silver"> <ItemStyle Width="10%" HorizontalAlign="Center" /> <ItemTemplate> <asp:CheckBox ID="chkFocusArea" runat="server" OnCheckedChanged="OnCheckChangedEvent" AutoPostBack="true" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </td> </tr> <tr> <td align="left"> <asp:TextBox ID="txtFocusArea" runat="server" Width="300px" CausesValidation="true" CssClass="txtStyle" ValidationGroup="focusArea"> </asp:TextBox> <cc1:TextBoxWatermarkExtender ID="txtFocusAreaWaterMark" runat="server" TargetControlID="txtFocusArea" WatermarkText="Add Focus Area" WatermarkCssClass="WaterMarkStyle"> </cc1:TextBoxWatermarkExtender> <asp:Button ID="btnAddFocusArea" runat="server" Text="AddFocusArea" CssClass="btnStyle" OnClick="btnAddFocusArea_Click" CausesValidation="true" ValidationGroup="focusArea" /> <asp:RequiredFieldValidator ID="reqtxtFocusArea" runat="server" ControlToValidate="txtFocusArea" ErrorMessage="Please enter focus area" Display="Dynamic" ValidationGroup="focusArea"> </asp:RequiredFieldValidator> <asp:RegularExpressionValidator ID="regexFocusArea" runat="server" ErrorMessage="Invalid characters(<,>,#)" ControlToValidate="txtFocusArea" ValidationExpression="^([^&lt;#&gt;]*)$" ValidationGroup="focusArea" Display="Dynamic" SetFocusOnError="true"> </asp:RegularExpressionValidator> </td> </tr> </table> </asp:Panel> and in code behind protected void btnAddFocusArea_Click(object sender, EventArgs e) { string strFocusArea = txtFocusArea.Text; OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]); if (strFocusArea == string.Empty || strFocusArea == txtFocusAreaWaterMark.WatermarkText) { lblError.Text = "Focus area is not entered"; } else { string insertQuery = "INSERT INTO LK_CODECAT_FOCUS_AREA(FOCUS_AREA_NAME,FK_ADDED_BY,ADDED_ON) "+ " VALUES('" + strFocusArea + "', "+Session["UserID"] +", GETDATE())"; try { myConnection.Open(); OleDbCommand myCommandToInsert = new OleDbCommand(insertQuery, myConnection); myCommandToInsert.ExecuteNonQuery(); } catch(Exception exc) { ExceptionLogger.LogException(exc); } finally { if (myConnection != null) { myConnection.Close(); } } PopulateFocusArea(); } txtFocusArea.Text = txtFocusAreaWaterMark.WatermarkText; } private void PopulateFocusArea() { OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]); string selectQuery = "SELECT PK_ID, FOCUS_AREA_NAME, IS_CURRENT_FOCUS FROM LK_CODECAT_FOCUS_AREA LKCFA ORDER BY FOCUS_AREA_NAME"; if (Session["RoleID"].ToString() == "1" || ((Session["WorkID"].ToString() != "9") || (Session["WorkID2"].ToString() != "9") || (Session["WorkID3"].ToString() != "9"))) { try { myConnection.Open(); OleDbCommand myCommandFocusArea = new OleDbCommand(selectQuery, myConnection); OleDbDataAdapter myAdapter = new OleDbDataAdapter(myCommandFocusArea); DataSet ds = new DataSet(); myAdapter.Fill(ds); dgFocusAreaDetails.DataSource = ds; dgFocusAreaDetails.ShowHeader = true; dgFocusAreaDetails.DataBind(); } catch (Exception exc) { ExceptionLogger.LogException(exc); } finally { if (myConnection != null) { myConnection.Close(); } } } } protected void dgFocusAreaDetails_SelectedIndexChanged(object sender, EventArgs e) { string selectedCategory = dgFocusAreaDetails.SelectedRow.Cells[1].Text; int index = dgFocusAreaDetails.SelectedIndex; lblError.Text = dgFocusAreaDetails.DataKeys[index].Value.ToString(); } public void OnCheckChangedEvent(object sender, EventArgs e) { CheckBox chk = (CheckBox)sender; string chkfocusarea = ((Control)chk).ID; //string focusAreaDetails = dgFocusAreaDetails.SelectedRow.Cells[0].Text; int index =Convert.ToInt32(dgFocusAreaDetails.SelectedIndex); if (chk.Checked) { string updateQuery = "UPDATE [LK_CODECAT_FOCUS_AREA] SET [IS_CURRENT_FOCUS] = 1 WHERE PK_ID = " +Convert.ToInt32( dgFocusAreaDetails.DataKeys[index].Value)+" "; } else { lblError.Text = "unchecked"; } } i want to know how i find the datakeyvalue on checked event.

    Read the article

  • How to retrieve ID of button clicked within usercontrol on Asp.net page?

    - by Shawn Gilligan
    I have a page that I am working on that I'm linking multiple user controls to. The user control contains 3 buttons, an attach, clear and view button. When a user clicks on any control on the page, the resulting information is "dumped" into the last visible control on the page. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" MasterPageFile="DefaultPage.master" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %> <%@ Register tagName="FileHandler" src="FileHandling.ascx" tagPrefix="ucFile" %> <asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server"> <asp:UpdatePanel ID="upPanel" UpdateMode="Conditional" runat="server"> <ContentTemplate> <table> <tr> <td> <ucFile:FileHandler ID="fFile1" runat="server" /> </td> <td> <ucFile:FileHandler ID="fFile2" runat="server" /> </td> </tr> </table> </ContentTemplate> </asp:UpdatePanel> </asp:Content> All file handling and processing is handled within the control, with an event when the upload to the file server is complete via a file name that was generated. When either button is clicked, the file name is always stored internal to the control in the last control's text box. Control code: <table style="width: 50%;"> <tr style="white-space: nowrap;"> <td style="width: 1%;"> <asp:Label runat="server" ID="lblFile" /> </td> <td style="width: 20%;"> <asp:TextBox ID="txtFile" CssClass="backColor" runat="server" OnTextChanged="FileInformationChanged" /> </td> <td style="width: 1%"> <%--<asp:Button runat="server" ID="btnUpload" CssClass="btn" Text="Attach" OnClick="UploadFile"/>--%> <input type="button" id="btnUpload" class="btn" tabindex="30" value="Attach" onclick="SetupUpload();" /> </td> <td style="width: 1%"> <%--<asp:Button runat="server" ID="btnClear" Text="Clear" CssClass="btn" OnClick="ClearTextValue"/>--%> <input type="button" id="btnClearFile" class="btn" value="Clear" onclick="document.getElementById('<%=txtFile.ClientID%>').value = '';document.getElementById('<%=hfFile.ClientID%>').value = '';" /> </td> <td style="width: 1%"> <a href="#here" onclick="ViewLink(document.getElementById('<%=hfFile.ClientID%>').value, '')">View</a> </td> <td style="width: 1%"> <asp:HiddenField ID="hfFile" runat="server" /> </td> </tr> </table> <script type="text/javascript"> var ItemPath = ""; function SetupUpload(File) { ItemPath = File; VersionAttach('<%=UploadPath%>', 'true'); } function UploadComplete(File) { document.getElementById('<%=txtFile.ClientID%>').value = File.substring(File.lastIndexOf("/") + 1); document.getElementById('<%=hfFile.ClientID%>').value = File; alert('<%=txtFile.Text %>'); alert('<%=ClientID %>') } function ViewLink(File, Alert) { if (File != "") { if (File.indexOf("../data/") != -1) { window.open(File, '_blank'); } else { window.open('../data/<%=UploadPath%>/' + File, '_blank'); } } else if (Alert == "") { alert('No file has been uploaded for this field.'); } } </script>

    Read the article

  • Referencing ASP.net textbox data in JavaScripts

    - by GoldenEarring
    I'm interested in making an interactive 3D pie chart using JavaScript and ASP.net controls for a webpage. Essentially, I want to make an interactive version of the chart here: https://google-developers.appspot.com/chart/interactive/docs/gallery/piechart#3D I want to have 5 ASP.net textboxes where the user enters data and then submits it, and the chart adjusts according to what the user enters. I understand using ASP.net controls with JS is probably not the most effective way to go about it, but I would really appreciate if someone could share how doing this would be possible. I really don't know where to begin. Thanks for any help! <%@ Page Language="C#" %> <!DOCTYPE html> <script runat="server"> void btn1_Click(object sender, EventArgs e) { double s = 0.0; double b = 0; double g = 0.0f; double c = 0.0f; double h = 0.0f; s = double.Parse(txtWork.Text); b = double.Parse(txtEat.Text); g = double.Parse(txtCommute.Text); c = double.Parse(txtWatchTV.Text); h = double.Parse(txtSleep.Text); double total = s + b + g + c + h; if (total != 24) { lblError.Text = "Warning! A day has 24 hours"; } if (total == 24) { lblError.Text = string.Empty; } } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", { packages: ["corechart"] }); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); var options = { title: 'My Daily Activities', is3D: true, }; var chart = new google.visualization.PieChart(document.getElementById('piechart_3d')); chart.draw(data, options); } var data = new google.visualization.DataTable(); var txtWork = document.getElementById('<%=txtWork.ClientID%>') txtEat = document.getElementById('<%=txtEat.ClientID%>') txtCommute = document.getElementById('<%=txtCommute.ClientID%>') txtWatchTV = document.getElementById('<%=txtWatchTV.ClientID%>') txtSleep = document.getElementById('<%=txtSleep.ClientID%>'); var workvalue = parseInt(txtWork, 10) var eatvalue = parseInt(txtEat, 10) var commutevalue = parseInt(txtCommute, 10) var watchtvvalue = parseInt(txtWatchTV, 10) var sleepvalue = parseInt(txtSleep, 10) // Declare columns data.addColumn('string', 'Task'); data.addColumn('Number', 'Hours per day'); // Add data. data.addRows([ ['Work', workvalue], ['Eat', eatvalue], ['Commute', commutevalue], ['Watch TV', watchtvvalue], ['Sleep', sleepvalue], ]); </script> </head> <body> <form id="form1" runat="server"> <div id="piechart_3d" style="width: 900px; height: 500px;"> </div> <asp:Label ID="lblError" runat="server" Font-Size="X-Large" Font-Bold="true" /> <table> <tr> <td>Work:</td> <td><asp:TextBox ID="txtWork" Text="11" runat="server" /></td> </tr> <tr> <td>Eat:</td> <td><asp:TextBox ID="txtEat" text="2" runat="server" /></td> </tr> <tr> <td>Commute:</td> <td><asp:TextBox ID="txtCommute" Text="2" runat="server" /></td> </tr> <tr> <td>Watch TV:</td> <td><asp:TextBox ID="txtWatchTV" Text="2" runat="server" /></td> </tr> <tr> <td>Sleep:</td> <td><asp:TextBox ID="txtSleep" Text="7" runat="server" /></td> </tr> </table> <br /> <br /> <asp:Button ID="btn1" text="Draw 3D PieChart" runat="server" OnClick="btn1_Click" /> </form> </body> </html>

    Read the article

  • What's New in ASP.NET 4

    - by Navaneeth
    The .NET Framework version 4 includes enhancements for ASP.NET 4 in targeted areas. Visual Studio 2010 and Microsoft Visual Web Developer Express also include enhancements and new features for improved Web development. This document provides an overview of many of the new features that are included in the upcoming release. This topic contains the following sections: ASP.NET Core Services ASP.NET Web Forms ASP.NET MVC Dynamic Data ASP.NET Chart Control Visual Web Developer Enhancements Web Application Deployment with Visual Studio 2010 Enhancements to ASP.NET Multi-Targeting ASP.NET Core Services ASP.NET 4 introduces many features that improve core ASP.NET services such as output caching and session state storage. Extensible Output Caching Since the time that ASP.NET 1.0 was released, output caching has enabled developers to store the generated output of pages, controls, and HTTP responses in memory. On subsequent Web requests, ASP.NET can serve content more quickly by retrieving the generated output from memory instead of regenerating the output from scratch. However, this approach has a limitation — generated content always has to be stored in memory. On servers that experience heavy traffic, the memory requirements for output caching can compete with memory requirements for other parts of a Web application. ASP.NET 4 adds extensibility to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. These storage options can include local or remote disks, cloud storage, and distributed cache engines. Output-cache provider extensibility in ASP.NET 4 lets you design more aggressive and more intelligent output-caching strategies for Web sites. For example, you can create an output-cache provider that caches the "Top 10" pages of a site in memory, while caching pages that get lower traffic on disk. Alternatively, you can cache every vary-by combination for a rendered page, but use a distributed cache so that the memory consumption is offloaded from front-end Web servers. You create a custom output-cache provider as a class that derives from the OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element For more information and for examples that show how to configure the output cache, see outputCache Element for caching (ASP.NET Settings Schema). For more information about the classes that support caching, see the documentation for the OutputCache and OutputCacheProvider classes. By default, in ASP.NET 4, all HTTP responses, rendered pages, and controls use the in-memory output cache. The defaultProvider attribute for ASP.NET is AspNetInternalProvider. You can change the default output-cache provider used for a Web application by specifying a different provider name for defaultProvider attribute. In addition, you can select different output-cache providers for individual control and for individual requests and programmatically specify which provider to use. For more information, see the HttpApplication.GetOutputCacheProviderName(HttpContext) method. The easiest way to choose a different output-cache provider for different Web user controls is to do so declaratively by using the new providerName attribute in a page or control directive, as shown in the following example: <%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %> Preloading Web Applications Some Web applications must load large amounts of data or must perform expensive initialization processing before serving the first request. In earlier versions of ASP.NET, for these situations you had to devise custom approaches to "wake up" an ASP.NET application and then run initialization code during the Application_Load method in the Global.asax file. To address this scenario, a new application preload manager (autostart feature) is available when ASP.NET 4 runs on IIS 7.5 on Windows Server 2008 R2. The preload feature provides a controlled approach for starting up an application pool, initializing an ASP.NET application, and then accepting HTTP requests. It lets you perform expensive application initialization prior to processing the first HTTP request. For example, you can use the application preload manager to initialize an application and then signal a load-balancer that the application was initialized and ready to accept HTTP traffic. To use the application preload manager, an IIS administrator sets an application pool in IIS 7.5 to be automatically started by using the following configuration in the applicationHost.config file: <applicationPools> <add name="MyApplicationPool" startMode="AlwaysRunning" /> </applicationPools> Because a single application pool can contain multiple applications, you specify individual applications to be automatically started by using the following configuration in the applicationHost.config file: <sites> <site name="MySite" id="1"> <application path="/" serviceAutoStartEnabled="true" serviceAutoStartProvider="PrewarmMyCache" > <!-- Additional content --> </application> </site> </sites> <!-- Additional content --> <serviceAutoStartProviders> <add name="PrewarmMyCache" type="MyNamespace.CustomInitialization, MyLibrary" /> </serviceAutoStartProviders> When an IIS 7.5 server is cold-started or when an individual application pool is recycled, IIS 7.5 uses the information in the applicationHost.config file to determine which Web applications have to be automatically started. For each application that is marked for preload, IIS7.5 sends a request to ASP.NET 4 to start the application in a state during which the application temporarily does not accept HTTP requests. When it is in this state, ASP.NET instantiates the type defined by the serviceAutoStartProvider attribute (as shown in the previous example) and calls into its public entry point. You create a managed preload type that has the required entry point by implementing the IProcessHostPreloadClient interface, as shown in the following example: public class CustomInitialization : System.Web.Hosting.IProcessHostPreloadClient { public void Preload(string[] parameters) { // Perform initialization. } } After your initialization code runs in the Preload method and after the method returns, the ASP.NET application is ready to process requests. Permanently Redirecting a Page Content in Web applications is often moved over the lifetime of the application. This can lead to links to be out of date, such as the links that are returned by search engines. In ASP.NET, developers have traditionally handled requests to old URLs by using the Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 (Found) response (which is used for a temporary redirect). This results in an extra HTTP round trip. ASP.NET 4 adds a RedirectPermanent helper method that makes it easy to issue HTTP 301 (Moved Permanently) responses, as in the following example: RedirectPermanent("/newpath/foroldcontent.aspx"); Search engines and other user agents that recognize permanent redirects will store the new URL that is associated with the content, which eliminates the unnecessary round trip made by the browser for temporary redirects. Session State Compression By default, ASP.NET provides two options for storing session state across a Web farm. The first option is a session state provider that invokes an out-of-process session state server. The second option is a session state provider that stores data in a Microsoft SQL Server database. Because both options store state information outside a Web application's worker process, session state has to be serialized before it is sent to remote storage. If a large amount of data is saved in session state, the size of the serialized data can become very large. ASP.NET 4 introduces a new compression option for both kinds of out-of-process session state providers. By using this option, applications that have spare CPU cycles on Web servers can achieve substantial reductions in the size of serialized session state data. You can set this option using the new compressionEnabled attribute of the sessionState element in the configuration file. When the compressionEnabled configuration option is set to true, ASP.NET compresses (and decompresses) serialized session state by using the .NET Framework GZipStreamclass. The following example shows how to set this attribute. <sessionState mode="SqlServer" sqlConnectionString="data source=dbserver;Initial Catalog=aspnetstate" allowCustomSqlDatabase="true" compressionEnabled="true" /> ASP.NET Web Forms Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been in this area for ASP.NET 4, such as the following: The ability to set meta tags. More control over view state. Support for recently introduced browsers and devices. Easier ways to work with browser capabilities. Support for using ASP.NET routing with Web Forms. More control over generated IDs. The ability to persist selected rows in data controls. More control over rendered HTML in the FormView and ListView controls. Filtering support for data source controls. Enhanced support for Web standards and accessibility Setting Meta Tags with the Page.MetaKeywords and Page.MetaDescription Properties Two properties have been added to the Page class: MetaKeywords and MetaDescription. These two properties represent corresponding meta tags in the HTML rendered for a page, as shown in the following example: <head id="Head1" runat="server"> <title>Untitled Page</title> <meta name="keywords" content="keyword1, keyword2' /> <meta name="description" content="Description of my page" /> </head> These two properties work like the Title property does, and they can be set in the @ Page directive. For more information, see Page.MetaKeywords and Page.MetaDescription. Enabling View State for Individual Controls A new property has been added to the Control class: ViewStateMode. You can use this property to disable view state for all controls on a page except those for which you explicitly enable view state. View state data is included in a page's HTML and increases the amount of time it takes to send a page to the client and post it back. Storing more view state than is necessary can cause significant decrease in performance. In earlier versions of ASP.NET, you could reduce the impact of view state on a page's performance by disabling view state for specific controls. But sometimes it is easier to enable view state for a few controls that need it instead of disabling it for many that do not need it. For more information, see Control.ViewStateMode. Support for Recently Introduced Browsers and Devices ASP.NET includes a feature that is named browser capabilities that lets you determine the capabilities of the browser that a user is using. Browser capabilities are represented by the HttpBrowserCapabilities object which is stored in the HttpRequest.Browser property. Information about a particular browser's capabilities is defined by a browser definition file. In ASP.NET 4, these browser definition files have been updated to contain information about recently introduced browsers and devices such as Google Chrome, Research in Motion BlackBerry smart phones, and Apple iPhone. Existing browser definition files have also been updated. For more information, see How to: Upgrade an ASP.NET Web Application to ASP.NET 4 and ASP.NET Web Server Controls and Browser Capabilities. The browser definition files that are included with ASP.NET 4 are shown in the following list: •blackberry.browser •chrome.browser •Default.browser •firefox.browser •gateway.browser •generic.browser •ie.browser •iemobile.browser •iphone.browser •opera.browser •safari.browser A New Way to Define Browser Capabilities ASP.NET 4 includes a new feature referred to as browser capabilities providers. As the name suggests, this lets you build a provider that in turn lets you write custom code to determine browser capabilities. In ASP.NET version 3.5 Service Pack 1, you define browser capabilities in an XML file. This file resides in a machine-level folder or an application-level folder. Most developers do not need to customize these files, but for those who do, the provider approach can be easier than dealing with complex XML syntax. The provider approach makes it possible to simplify the process by implementing a common browser definition syntax, or a database that contains up-to-date browser definitions, or even a Web service for such a database. For more information about the new browser capabilities provider, see the What's New for ASP.NET 4 White Paper. Routing in ASP.NET 4 ASP.NET 4 adds built-in support for routing with Web Forms. Routing is a feature that was introduced with ASP.NET 3.5 SP1 and lets you configure an application to use URLs that are meaningful to users and to search engines because they do not have to specify physical file names. This can make your site more user-friendly and your site content more discoverable by search engines. For example, the URL for a page that displays product categories in your application might look like the following example: http://website/products.aspx?categoryid=12 By using routing, you can use the following URL to render the same information: http://website/products/software The second URL lets the user know what to expect and can result in significantly improved rankings in search engine results. the new features include the following: The PageRouteHandler class is a simple HTTP handler that you use when you define routes. You no longer have to write a custom route handler. The HttpRequest.RequestContext and Page.RouteData properties make it easier to access information that is passed in URL parameters. The RouteUrl expression provides a simple way to create a routed URL in markup. The RouteValue expression provides a simple way to extract URL parameter values in markup. The RouteParameter class makes it easier to pass URL parameter values to a query for a data source control (similar to FormParameter). You no longer have to change the Web.config file to enable routing. For more information about routing, see the following topics: ASP.NET Routing Walkthrough: Using ASP.NET Routing in a Web Forms Application How to: Define Routes for Web Forms Applications How to: Construct URLs from Routes How to: Access URL Parameters in a Routed Page Setting Client IDs The new ClientIDMode property makes it easier to write client script that references HTML elements rendered for server controls. Increasing use of Microsoft Ajax makes the need to do this more common. For example, you may have a data control that renders a long list of products with prices and you want to use client script to make a Web service call and update individual prices in the list as they change without refreshing the entire page. Typically you get a reference to an HTML element in client script by using the document.GetElementById method. You pass to this method the value of the id attribute of the HTML element you want to reference. In the case of elements that are rendered for ASP.NET server controls earlier versions of ASP.NET could make this difficult or impossible. You were not always able to predict what id values ASP.NET would generate, or ASP.NET could generate very long id values. The problem was especially difficult for data controls that would generate multiple rows for a single instance of the control in your markup. ASP.NET 4 adds two new algorithms for generating id attributes. These algorithms can generate id attributes that are easier to work with in client script because they are more predictable and that are easier to work with because they are simpler. For more information about how to use the new algorithms, see the following topics: ASP.NET Web Server Control Identification Walkthrough: Making Data-Bound Controls Easier to Access from JavaScript Walkthrough: Making Controls Located in Web User Controls Easier to Access from JavaScript How to: Access Controls from JavaScript by ID Persisting Row Selection in Data Controls The GridView and ListView controls enable users to select a row. In previous versions of ASP.NET, row selection was based on the row index on the page. For example, if you select the third item on page 1 and then move to page 2, the third item on page 2 is selected. In most cases, is more desirable not to select any rows on page 2. ASP.NET 4 supports Persisted Selection, a new feature that was initially supported only in Dynamic Data projects in the .NET Framework 3.5 SP1. When this feature is enabled, the selected item is based on the row data key. This means that if you select the third row on page 1 and move to page 2, nothing is selected on page 2. When you move back to page 1, the third row is still selected. This is a much more natural behavior than the behavior in earlier versions of ASP.NET. Persisted selection is now supported for the GridView and ListView controls in all projects. You can enable this feature in the GridView control, for example, by setting the EnablePersistedSelection property, as shown in the following example: <asp:GridView id="GridView2" runat="server" PersistedSelection="true"> </asp:GridView> FormView Control Enhancements The FormView control is enhanced to make it easier to style the content of the control with CSS. In previous versions of ASP.NET, the FormView control rendered it contents using an item template. This made styling more difficult in the markup because unexpected table row and table cell tags were rendered by the control. The FormView control supports RenderOuterTable, a property in ASP.NET 4. When this property is set to false, as show in the following example, the table tags are not rendered. This makes it easier to apply CSS style to the contents of the control. <asp:FormView ID="FormView1" runat="server" RenderTable="false"> For more information, see FormView Web Server Control Overview. ListView Control Enhancements The ListView control, which was introduced in ASP.NET 3.5, has all the functionality of the GridView control while giving you complete control over the output. This control has been made easier to use in ASP.NET 4. The earlier version of the control required that you specify a layout template that contained a server control with a known ID. The following markup shows a typical example of how to use the ListView control in ASP.NET 3.5. <asp:ListView ID="ListView1" runat="server"> <LayoutTemplate> <asp:PlaceHolder ID="ItemPlaceHolder" runat="server"></asp:PlaceHolder> </LayoutTemplate> <ItemTemplate> <% Eval("LastName")%> </ItemTemplate> </asp:ListView> In ASP.NET 4, the ListView control does not require a layout template. The markup shown in the previous example can be replaced with the following markup: <asp:ListView ID="ListView1" runat="server"> <ItemTemplate> <% Eval("LastName")%> </ItemTemplate> </asp:ListView> For more information, see ListView Web Server Control Overview. Filtering Data with the QueryExtender Control A very common task for developers who create data-driven Web pages is to filter data. This traditionally has been performed by building Where clauses in data source controls. This approach can be complicated, and in some cases the Where syntax does not let you take advantage of the full functionality of the underlying database. To make filtering easier, a new QueryExtender control has been added in ASP.NET 4. This control can be added to EntityDataSource or LinqDataSource controls in order to filter the data returned by these controls. Because the QueryExtender control relies on LINQ, but you do not to need to know how to write LINQ queries to use the query extender. The QueryExtender control supports a variety of filter options. The following lists QueryExtender filter options. Term Definition SearchExpression Searches a field or fields for string values and compares them to a specified string value. RangeExpression Searches a field or fields for values in a range specified by a pair of values. PropertyExpression Compares a specified value to a property value in a field. If the expression evaluates to true, the data that is being examined is returned. OrderByExpression Sorts data by a specified column and sort direction. CustomExpression Calls a function that defines custom filter in the page. For more information, see QueryExtenderQueryExtender Web Server Control Overview. Enhanced Support for Web Standards and Accessibility Earlier versions of ASP.NET controls sometimes render markup that does not conform to HTML, XHTML, or accessibility standards. ASP.NET 4 eliminates most of these exceptions. For details about how the HTML that is rendered by each control meets accessibility standards, see ASP.NET Controls and Accessibility. CSS for Controls that Can be Disabled In ASP.NET 3.5, when a control is disabled (see WebControl.Enabled), a disabled attribute is added to the rendered HTML element. For example, the following markup creates a Label control that is disabled: <asp:Label id="Label1" runat="server"   Text="Test" Enabled="false" /> In ASP.NET 3.5, the previous control settings generate the following HTML: <span id="Label1" disabled="disabled">Test</span> In HTML 4.01, the disabled attribute is not considered valid on span elements. It is valid only on input elements because it specifies that they cannot be accessed. On display-only elements such as span elements, browsers typically support rendering for a disabled appearance, but a Web page that relies on this non-standard behavior is not robust according to accessibility standards. For display-only elements, you should use CSS to indicate a disabled visual appearance. Therefore, by default ASP.NET 4 generates the following HTML for the control settings shown previously: <span id="Label1" class="aspNetDisabled">Test</span> You can change the value of the class attribute that is rendered by default when a control is disabled by setting the DisabledCssClass property. CSS for Validation Controls In ASP.NET 3.5, validation controls render a default color of red as an inline style. For example, the following markup creates a RequiredFieldValidator control: <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"   ErrorMessage="Required Field" ControlToValidate="RadioButtonList1" /> ASP.NET 3.5 renders the following HTML for the validator control: <span id="RequiredFieldValidator1"   style="color:Red;visibility:hidden;">RequiredFieldValidator</span> By default, ASP.NET 4 does not render an inline style to set the color to red. An inline style is used only to hide or show the validator, as shown in the following example: <span id="RequiredFieldValidator1"   style"visibility:hidden;">RequiredFieldValidator</span> Therefore, ASP.NET 4 does not automatically show error messages in red. For information about how to use CSS to specify a visual style for a validation control, see Validating User Input in ASP.NET Web Pages. CSS for the Hidden Fields Div Element ASP.NET uses hidden fields to store state information such as view state and control state. These hidden fields are contained by a div element. In ASP.NET 3.5, this div element does not have a class attribute or an id attribute. Therefore, CSS rules that affect all div elements could unintentionally cause this div to be visible. To avoid this problem, ASP.NET 4 renders the div element for hidden fields with a CSS class that you can use to differentiate the hidden fields div from others. The new classvalue is shown in the following example: <div class="aspNetHidden"> CSS for the Table, Image, and ImageButton Controls By default, in ASP.NET 3.5, some controls set the border attribute of rendered HTML to zero (0). The following example shows HTML that is generated by the Table control in ASP.NET 3.5: <table id="Table2" border="0"> The Image control and the ImageButton control also do this. Because this is not necessary and provides visual formatting information that should be provided by using CSS, the attribute is not generated in ASP.NET 4. CSS for the UpdatePanel and UpdateProgress Controls In ASP.NET 3.5, the UpdatePanel and UpdateProgress controls do not support expando attributes. This makes it impossible to set a CSS class on the HTMLelements that they render. In ASP.NET 4 these controls have been changed to accept expando attributes, as shown in the following example: <asp:UpdatePanel runat="server" class="myStyle"> </asp:UpdatePanel> The following HTML is rendered for this markup: <div id="ctl00_MainContent_UpdatePanel1" class="expandoclass"> </div> Eliminating Unnecessary Outer Tables In ASP.NET 3.5, the HTML that is rendered for the following controls is wrapped in a table element whose purpose is to apply inline styles to the entire control: FormView Login PasswordRecovery ChangePassword If you use templates to customize the appearance of these controls, you can specify CSS styles in the markup that you provide in the templates. In that case, no extra outer table is required. In ASP.NET 4, you can prevent the table from being rendered by setting the new RenderOuterTable property to false. Layout Templates for Wizard Controls In ASP.NET 3.5, the Wizard and CreateUserWizard controls generate an HTML table element that is used for visual formatting. In ASP.NET 4 you can use a LayoutTemplate element to specify the layout. If you do this, the HTML table element is not generated. In the template, you create placeholder controls to indicate where items should be dynamically inserted into the control. (This is similar to how the template model for the ListView control works.) For more information, see the Wizard.LayoutTemplate property. New HTML Formatting Options for the CheckBoxList and RadioButtonList Controls ASP.NET 3.5 uses HTML table elements to format the output for the CheckBoxList and RadioButtonList controls. To provide an alternative that does not use tables for visual formatting, ASP.NET 4 adds two new options to the RepeatLayout enumeration: UnorderedList. This option causes the HTML output to be formatted by using ul and li elements instead of a table. OrderedList. This option causes the HTML output to be formatted by using ol and li elements instead of a table. For examples of HTML that is rendered for the new options, see the RepeatLayout enumeration. Header and Footer Elements for the Table Control In ASP.NET 3.5, the Table control can be configured to render thead and tfoot elements by setting the TableSection property of the TableHeaderRow class and the TableFooterRow class. In ASP.NET 4 these properties are set to the appropriate values by default. CSS and ARIA Support for the Menu Control In ASP.NET 3.5, the Menu control uses HTML table elements for visual formatting, and in some configurations it is not keyboard-accessible. ASP.NET 4 addresses these problems and improves accessibility in the following ways: The generated HTML is structured as an unordered list (ul and li elements). CSS is used for visual formatting. The menu behaves in accordance with ARIA standards for keyboard access. You can use arrow keys to navigate menu items. (For information about ARIA, see Accessibility in Visual Studio and ASP.NET.) ARIA role and property attributes are added to the generated HTML. (Attributes are added by using JavaScript instead of included in the HTML, to avoid generating HTML that would cause markup validation errors.) Styles for the Menu control are rendered in a style block at the top of the page, instead of inline with the rendered HTML elements. If you want to use a separate CSS file so that you can modify the menu styles, you can set the Menu control's new IncludeStyleBlock property to false, in which case the style block is not generated. Valid XHTML for the HtmlForm Control In ASP.NET 3.5, the HtmlForm control (which is created implicitly by the <form runat="server"> tag) renders an HTML form element that has both name and id attributes. The name attribute is deprecated in XHTML 1.1. Therefore, this control does not render the name attribute in ASP.NET 4. Maintaining Backward Compatibility in Control Rendering An existing ASP.NET Web site might have code in it that assumes that controls are rendering HTML the way they do in ASP.NET 3.5. To avoid causing backward compatibility problems when you upgrade the site to ASP.NET 4, you can have ASP.NET continue to generate HTML the way it does in ASP.NET 3.5 after you upgrade the site. To do so, you can set the controlRenderingCompatibilityVersion attribute of the pages element to "3.5" in the Web.config file of an ASP.NET 4 Web site, as shown in the following example: <system.web>   <pages controlRenderingCompatibilityVersion="3.5"/> </system.web> If this setting is omitted, the default value is the same as the version of ASP.NET that the Web site targets. (For information about multi-targeting in ASP.NET, see .NET Framework Multi-Targeting for ASP.NET Web Projects.) ASP.NET MVC ASP.NET MVC helps Web developers build compelling standards-based Web sites that are easy to maintain because it decreases the dependency among application layers by using the Model-View-Controller (MVC) pattern. MVC provides complete control over the page markup. It also improves testability by inherently supporting Test Driven Development (TDD). Web sites created using ASP.NET MVC have a modular architecture. This allows members of a team to work independently on the various modules and can be used to improve collaboration. For example, developers can work on the model and controller layers (data and logic), while the designer work on the view (presentation). For tutorials, walkthroughs, conceptual content, code samples, and a complete API reference, see ASP.NET MVC 2. Dynamic Data Dynamic Data was introduced in the .NET Framework 3.5 SP1 release in mid-2008. This feature provides many enhancements for creating data-driven applications, such as the following: A RAD experience for quickly building a data-driven Web site. Automatic validation that is based on constraints defined in the data model. The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project. For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. For more information, see ASP.NET Dynamic Data Content Map. Enabling Dynamic Data for Individual Data-Bound Controls in Existing Web Applications You can use Dynamic Data features in existing ASP.NET Web applications that do not use scaffolding by enabling Dynamic Data for individual data-bound controls. Dynamic Data provides the presentation and data layer support for rendering these controls. When you enable Dynamic Data for data-bound controls, you get the following benefits: Setting default values for data fields. Dynamic Data enables you to provide default values at run time for fields in a data control. Interacting with the database without creating and registering a data model. Automatically validating the data that is entered by the user without writing any code. For more information, see Walkthrough: Enabling Dynamic Data in ASP.NET Data-Bound Controls. New Field Templates for URLs and E-mail Addresses ASP.NET 4 introduces two new built-in field templates, EmailAddress.ascx and Url.ascx. These templates are used for fields that are marked as EmailAddress or Url using the DataTypeAttribute attribute. For EmailAddress objects, the field is displayed as a hyperlink that is created by using the mailto: protocol. When users click the link, it opens the user's e-mail client and creates a skeleton message. Objects typed as Url are displayed as ordinary hyperlinks. The following example shows how to mark fields. [DataType(DataType.EmailAddress)] public object HomeEmail { get; set; } [DataType(DataType.Url)] public object Website { get; set; } Creating Links with the DynamicHyperLink Control Dynamic Data uses the new routing feature that was added in the .NET Framework 3.5 SP1 to control the URLs that users see when they access the Web site. The new DynamicHyperLink control makes it easy to build links to pages in a Dynamic Data site. For information, see How to: Create Table Action Links in Dynamic Data Support for Inheritance in the Data Model Both the ADO.NET Entity Framework and LINQ to SQL support inheritance in their data models. An example of this might be a database that has an InsurancePolicy table. It might also contain CarPolicy and HousePolicy tables that have the same fields as InsurancePolicy and then add more fields. Dynamic Data has been modified to understand inherited objects in the data model and to support scaffolding for the inherited tables. For more information, see Walkthrough: Mapping Table-per-Hierarchy Inheritance in Dynamic Data. Support for Many-to-Many Relationships (Entity Framework Only) The Entity Framework has rich support for many-to-many relationships between tables, which is implemented by exposing the relationship as a collection on an Entity object. New field templates (ManyToMany.ascx and ManyToMany_Edit.ascx) have been added to provide support for displaying and editing data that is involved in many-to-many relationships. For more information, see Working with Many-to-Many Data Relationships in Dynamic Data. New Attributes to Control Display and Support Enumerations The DisplayAttribute has been added to give you additional control over how fields are displayed. The DisplayNameAttribute attribute in earlier versions of Dynamic Data enabled you to change the name that is used as a caption for a field. The new DisplayAttribute class lets you specify more options for displaying a field, such as the order in which a field is displayed and whether a field will be used as a filter. The attribute also provides independent control of the name that is used for the labels in a GridView control, the name that is used in a DetailsView control, the help text for the field, and the watermark used for the field (if the field accepts text input). The EnumDataTypeAttribute class has been added to let you map fields to enumerations. When you apply this attribute to a field, you specify an enumeration type. Dynamic Data uses the new Enumeration.ascx field template to create UI for displaying and editing enumeration values. The template maps the values from the database to the names in the enumeration. Enhanced Support for Filters Dynamic Data 1.0 had built-in filters for Boolean columns and foreign-key columns. The filters did not let you specify the order in which they were displayed. The new DisplayAttribute attribute addresses this by giving you control over whether a column appears as a filter and in what order it will be displayed. An additional enhancement is that filtering support has been rewritten to use the new QueryExtender feature of Web Forms. This lets you create filters without requiring knowledge of the data source control that the filters will be used with. Along with these extensions, filters have also been turned into template controls, which lets you add new ones. Finally, the DisplayAttribute class mentioned earlier allows the default filter to be overridden, in the same way that UIHint allows the default field template for a column to be overridden. For more information, see Walkthrough: Filtering Rows in Tables That Have a Parent-Child Relationship and QueryableFilterRepeater. ASP.NET Chart Control The ASP.NET chart server control enables you to create ASP.NET pages applications that have simple, intuitive charts for complex statistical or financial analysis. The chart control supports the following features: Data series, chart areas, axes, legends, labels, titles, and more. Data binding. Data manipulation, such as copying, splitting, merging, alignment, grouping, sorting, searching, and filtering. Statistical formulas and financial formulas. Advanced chart appearance, such as 3-D, anti-aliasing, lighting, and perspective. Events and customizations. Interactivity and Microsoft Ajax. Support for the Ajax Content Delivery Network (CDN), which provides an optimized way for you to add Microsoft Ajax Library and jQuery scripts to your Web applications. For more information, see Chart Web Server Control Overview. Visual Web Developer Enhancements The following sections provide information about enhancements and new features in Visual Studio 2010 and Visual Web Developer Express. The Web page designer in Visual Studio 2010 has been enhanced for better CSS compatibility, includes additional support for HTML and ASP.NET markup snippets, and features a redesigned version of IntelliSense for JScript. Improved CSS Compatibility The Visual Web Developer designer in Visual Studio 2010 has been updated to improve CSS 2.1 standards compliance. The designer better preserves HTML source code and is more robust than in previous versions of Visual Studio. HTML and JScript Snippets In the HTML editor, IntelliSense auto-completes tag names. The IntelliSense Snippets feature auto-completes whole tags and more. In Visual Studio 2010, IntelliSense snippets are supported for JScript, alongside C# and Visual Basic, which were supported in earlier versions of Visual Studio. Visual Studio 2010 includes over 200 snippets that help you auto-complete common ASP.NET and HTML tags, including required attributes (such as runat="server") and common attributes specific to a tag (such as ID, DataSourceID, ControlToValidate, and Text). You can download additional snippets, or you can write your own snippets that encapsulate the blocks of markup that you or your team use for common tasks. For more information on HTML snippets, see Walkthrough: Using HTML Snippets. JScript IntelliSense Enhancements In Visual 2010, JScript IntelliSense has been redesigned to provide an even richer editing experience. IntelliSense now recognizes objects that have been dynamically generated by methods such as registerNamespace and by similar techniques used by other JavaScript frameworks. Performance has been improved to analyze large libraries of script and to display IntelliSense with little or no processing delay. Compatibility has been significantly increased to support almost all third-party libraries and to support diverse coding styles. Documentation comments are now parsed as you type and are immediately leveraged by IntelliSense. Web Application Deployment with Visual Studio 2010 For Web application projects, Visual Studio now provides tools that work with the IIS Web Deployment Tool (Web Deploy) to automate many processes that had to be done manually in earlier versions of ASP.NET. For example, the following tasks can now be automated: Creating an IIS application on the destination computer and configuring IIS settings. Copying files to the destination computer. Changing Web.config settings that must be different in the destination environment. Propagating changes to data or data structures in SQL Server databases that are used by the Web application. For more information about Web application deployment, see ASP.NET Deployment Content Map. Enhancements to ASP.NET Multi-Targeting ASP.NET 4 adds new features to the multi-targeting feature to make it easier to work with projects that target earlier versions of the .NET Framework. Multi-targeting was introduced in ASP.NET 3.5 to enable you to use the latest version of Visual Studio without having to upgrade existing Web sites or Web services to the latest version of the .NET Framework. In Visual Studio 2008, when you work with a project targeted for an earlier version of the .NET Framework, most features of the development environment adapt to the targeted version. However, IntelliSense displays language features that are available in the current version, and property windows display properties available in the current version. In Visual Studio 2010, only language features and properties available in the targeted version of the .NET Framework are shown. For more information about multi-targeting, see the following topics: .NET Framework Multi-Targeting for ASP.NET Web Projects ASP.NET Side-by-Side Execution Overview How to: Host Web Applications That Use Different Versions of the .NET Framework on the Same Server How to: Deploy Web Site Projects Targeted for Earlier Versions of the .NET Framework

    Read the article

  • C# ASP.NET AJAX CascadingDropDown Selected value propriety problem

    - by Eyla
    Greetings, I have a problem to use selected value propriety of CascadingDropDown. I have 3 asp dropdown controls with ajax CascadingDropDown for each one of them. I have no problem to bind data to the 3 CascadingDropDown but my problem is to rebind CascadingDropDown. simply what I want to do is to select a record from Gridview which has the selected values for the CascadingDropDown that I want to pass then rebind the CascadingDropDown with selected value. I'm posting my code down which include: 1-ASP.NET code. 2-Code behind to handle selected record from grid view. 3- web servisice that handle binding data to the 3 CascadingDropDown. please advice how to rebind data to CascadingDropDown with selected value. by the way I used selected value proprety as showning in my code but it is not working and there is no error. Thank you, ........................ ASP.NET code ........................ <%@ Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="IMAM_APPLICATION.WebForm1" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="idcontact_info" DataSourceID="ObjectDataSource1" onselectedindexchanged="GridView1_SelectedIndexChanged"> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:BoundField DataField="idcontact_info" HeaderText="idcontact_info" InsertVisible="False" ReadOnly="True" SortExpression="idcontact_info" /> <asp:BoundField DataField="Work_Field" HeaderText="Work_Field" SortExpression="Work_Field" /> <asp:BoundField DataField="Occupation" HeaderText="Occupation" SortExpression="Occupation" /> <asp:BoundField DataField="sub_Occupation" HeaderText="sub_Occupation" SortExpression="sub_Occupation" /> </Columns> </asp:GridView> <asp:Label ID="lbl" runat="server" Text="Label"></asp:Label> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}" SelectMethod="GetData" TypeName="IMAM_APPLICATION.DSContactTableAdapters.contact_infoTableAdapter" UpdateMethod="Update"> <DeleteParameters> <asp:Parameter Name="Original_idcontact_info" Type="Int32" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="Work_Field" Type="String" /> <asp:Parameter Name="Occupation" Type="String" /> <asp:Parameter Name="sub_Occupation" Type="String" /> <asp:Parameter Name="Original_idcontact_info" Type="Int32" /> </UpdateParameters> <InsertParameters> <asp:Parameter Name="Work_Field" Type="String" /> <asp:Parameter Name="Occupation" Type="String" /> <asp:Parameter Name="sub_Occupation" Type="String" /> </InsertParameters> </asp:ObjectDataSource> <asp:DropDownList ID="cmbWorkField" runat="server" Style="top: 715px; left: 180px; position: absolute; height: 22px; width: 126px"> </asp:DropDownList> <asp:DropDownList runat="server" ID="cmbOccupation" Style="top: 745px; left: 180px; position: absolute; height: 22px; width: 77px"> </asp:DropDownList> <asp:DropDownList ID="cmbSubOccup" runat="server" style="position:absolute; top: 775px; left: 180px;"> </asp:DropDownList> <cc1:CascadingDropDown ID="cmbWorkField_CascadingDropDown" runat="server" TargetControlID="cmbWorkField" Category="WorkField" LoadingText="Please Wait ..." PromptText="Select Wor kField ..." ServiceMethod="GetWorkField" ServicePath="ServiceTags.asmx"> </cc1:CascadingDropDown> <cc1:CascadingDropDown ID="cmbOccupation_CascadingDropDown" runat="server" TargetControlID="cmbOccupation" Category="Occup" LoadingText="Please wait..." PromptText="Select Occup ..." ServiceMethod="GetOccup" ServicePath="ServiceTags.asmx" ParentControlID="cmbWorkField"> </cc1:CascadingDropDown> <cc1:CascadingDropDown ID="cmbSubOccup_CascadingDropDown" runat="server" Category="SubOccup" Enabled="True" LoadingText="Please Wait..." ParentControlID="cmbOccupation" PromptText="Select Sub Occup" ServiceMethod="GetSubOccup" ServicePath="ServiceTags.asmx" TargetControlID="cmbSubOccup"> </cc1:CascadingDropDown> </asp:Content> ...................................................... C# code behind ...................................................... protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { string strg = GridView1.SelectedDataKey["idcontact_info"].ToString(); int index = Convert.ToInt32(GridView1.SelectedDataKey["idcontact_info"].ToString()); //txtSearch.Text = GridView1.SelectedIndex.ToString(); // txtSearch.Text = GridView1.SelectedDataKey["idcontact_info"].ToString(); DSContactTableAdapters.contact_infoTableAdapter GetByIDAdapter = new DSContactTableAdapters.contact_infoTableAdapter(); DSContact.contact_infoDataTable ByID = GetByIDAdapter.GetDataByID(index); //DSSearch.contact_infoDataTable FirstName = FirstNameAdapter.GetDataByFirstNameList(prefixText); foreach (DataRow dr in ByID.Rows) { lbl.Text = dr["Work_Field"].ToString() + "....." + dr["Occupation"].ToString() + "....." + dr["sub_Occupation"].ToString(); cmbWorkField_CascadingDropDown.SelectedValue = dr["Work_Field"].ToString(); cmbOccupation_CascadingDropDown.SelectedValue = dr["Occupation"].ToString(); cmbSubOccup_CascadingDropDown.SelectedValue = dr["sub_Occupation"].ToString(); } } ....................................................... web Service ....................................................... [WebMethod] public CascadingDropDownNameValue[] GetWorkField(string knownCategoryValues, string category) { //dsCarsTableAdapters.CarsTableAdapter makeAdapter = new dsCarsTableAdapters.CarsTableAdapter(); //dsCars.CarsDataTable makes = makeAdapter.GetAllCars(); DSContactTableAdapters.tag_work_fieldTableAdapter GetWorkFieldAdapter = new DSContactTableAdapters.tag_work_fieldTableAdapter(); DSContact.tag_work_fieldDataTable WorkFields = GetWorkFieldAdapter.GetDataByGetWorkField(); List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>(); foreach (DataRow dr in WorkFields) { string Work_Field = (string)dr["work_Field_name"]; int idtag_work_field = (int)dr["idtag_work_field"]; values.Add(new CascadingDropDownNameValue(Work_Field, idtag_work_field.ToString())); } return values.ToArray(); } [WebMethod] public CascadingDropDownNameValue[] GetOccup(string knownCategoryValues, string category) { StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues); int idtag_work_field; if (!kv.ContainsKey("WorkField") || !Int32.TryParse(kv["WorkField"], out idtag_work_field)) { return null; } //dsCarModelsTableAdapters.CarModelsTableAdapter modelAdapter = new dsCarModelsTableAdapters.CarModelsTableAdapter(); //dsCarModels.CarModelsDataTable models = modelAdapter.GetModelsByCarId(makeId); DSContactTableAdapters.tag_OccupTableAdapter GetOccupAdapter = new DSContactTableAdapters.tag_OccupTableAdapter(); DSContact.tag_OccupDataTable Occups = GetOccupAdapter.GetByOccup_ID(idtag_work_field); // List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>(); foreach (DataRow dr in Occups) { values.Add(new CascadingDropDownNameValue((string)dr["Occup_Name"], dr["idtag_Occup"].ToString())); } return values.ToArray(); } [WebMethod] public CascadingDropDownNameValue[] GetSubOccup(string knownCategoryValues, string category) { StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues); int idtag_Occup; if (!kv.ContainsKey("Occup") || !Int32.TryParse(kv["Occup"], out idtag_Occup)) { return null; } //dsModelColorsTableAdapters.ModelColorsTableAdapter adapter = new dsModelColorsTableAdapters.ModelColorsTableAdapter(); //dsModelColors.ModelColorsDataTable colors = adapter.GetColorsByModelId(colorId); DSContactTableAdapters.tag_Sub_OccupTableAdapter GetSubOccupAdapter = new DSContactTableAdapters.tag_Sub_OccupTableAdapter(); DSContact.tag_Sub_OccupDataTable SubOccups = GetSubOccupAdapter.GetDataBy_Sub_Occup_ID(idtag_Occup); List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>(); foreach (DataRow dr in SubOccups) { values.Add(new CascadingDropDownNameValue((string)dr["Sub_Occup_Name"], dr["idtag_Sub_Occup"].ToString())); } return values.ToArray(); }

    Read the article

  • ASP.NET make a panel visible on click of hyperlink (whilst also cuasing postback for page navigation

    - by Helen
    I may be asking the impossible but let me set out my problem: I have a menu in a MasterPage which uses images and mouseover mouseout events for design purposes. On one of the menu options I need to display a set of sub menus options on the click of the parent menu item. The menu item itself also needs to navigate to a specified url. I was originally trying to use an AJAX accordion panel but as I only had one accordion panel it was always displaying the sub menu items and was not collapsing. I have also tried putting the options in a div and setting the display via javascript. This worked but then was overwritten once the page navigation postback occurred. Here is the source: <%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <%@ Register Src="LeadHeader.ascx" TagName="LeadHeader" TagPrefix="uc1" %> <%@ Register Src="~/LeadFooter.ascx" TagName="LeadFooter" TagPrefix="uc2" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var revert = new Array(); var inames = new Array('home', 'whoweare', 'whatwedo','ourapproach', 'ourvalues', 'contact'); // Preload if (document.images) { var flipped = new Array(); for(i=0; i< inames.length; i++) { flipped[i] = new Image(); flipped[i].src = "images/"+inames[i]+"2.jpg"; } } function over(num) { if(document.images) { revert[num] = document.images[inames[num]].src; document.images[inames[num]].src = flipped[num].src; } } function out(num) { if(document.images) document.images[inames[num]].src = revert[num]; } function ShowHide(elementId) { var element = document.getElementById(elementId); if(element.style.display != "block") { element.style.display = "block"; } else { element.style.display = "none"; } } function UpdateText(element) { if(element.innerHTML.indexOf("Show") != -1) { element.innerHTML = "Hide Details"; } else { element.innerHTML = "Show Details"; } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server"> <uc1:LeadHeader ID="LeadHeader" runat="server" /> </asp:ContentPlaceHolder> <div id="nav"> <div class="menu-item"> <a href="Default.aspx"> <img src="Images/home.jpg" alt="home" id="home" onmouseover="over(0)" onmouseout="out(0)" class="right" /></a> </div> <div class="menu-item"> <a href="AboutUs.aspx"> <img src="Images/whoweare.jpg" alt="who we are" id="whoweare" onmouseover="over(1)" onmouseout="out(1)" class="right" /></a> </div> <%-- <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <cc1:Accordion ID="Accordion1" runat="server" AutoSize="None" FadeTransitions="true" TransitionDuration="350" FramesPerSecond="40" RequireOpenedPane="false" > <Panes> <cc1:AccordionPane runat="server"> <Header>--%> <div class="menu-item"> <a href="WhatWeDo.aspx"> <img src="Images/whatwedo.jpg" alt="what we do" id="whatwedo" onmouseover="over(2)" onmouseout="out(2)" class="right" onclick="ShowHide('divDetails');UpdateText(this);" /></a></div> <%--/Header> <Content>--%> <div id="divDetails" style="display:none;"> <a href="management.aspx" title="Management Development">Management Development</a><br /> <a href="leadership.aspx" title="Leadership Development">Leadership Development</a><br /> <a href="personal.aspx" title="Personal Development">Personal Development</a><br /> <a href="realteams.aspx" title="Team Building / Facilitation">Team Building & Facilitation</a><br /> <a href="coaching.aspx" title="Coaching">One to One Coaching</a> </div> <%-- </Content> </cc1:AccordionPane> </Panes> </cc1:Accordion> --%> <div class="menu-item"> <a href="OurApproach.aspx"> <img src="images/ourapproach.jpg" alt="our approach" id="ourapproach" onmouseover="over(3)" onmouseout="out(3)" /></a> </div> <div class="menu-item"> <a href="OurValues.aspx"> <img src="images/ourvalues.jpg" alt="our values" id="ourvalues" onmouseover="over(4)" onmouseout="out(4)" /></a> </div> <div class="menu-item"> <a href="ContactUs.aspx"> <img src="images/ContactUs.jpg" alt="contact us" id="contactus" onmouseover="over(5)" onmouseout="out(5)" /></a> </div> </div> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> <asp:ContentPlaceHolder ID="ContentPlaceHolder3" runat="server"> <uc2:LeadFooter ID="LeadFooter" runat="server" /> </asp:ContentPlaceHolder> </div> </form> </body> </html>

    Read the article

  • validation in datagrid while insert update in asp.net

    - by abhi
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" % <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" % Untitled Page   <telerik:GridTemplateColumn Visible="false"> <ItemTemplate> <asp:Label ID="lblEmpID" runat="server" Text='<%# bind("pid") %>'> </asp:Label> </ItemTemplate> </telerik:GridTemplateColumn> <telerik:GridBoundColumn UniqueName="Fname" HeaderText="Fname" DataField="Fname" CurrentFilterFunction="NotIsNull" SortExpression="Fname"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="Lname" HeaderText="Lname" DataField="Lname" CurrentFilterFunction="NotIsNull" SortExpression="Lname"> </telerik:GridBoundColumn> <telerik:GridBoundColumn UniqueName="Designation" HeaderText="Designation" DataField="Designation" CurrentFilterFunction="NotIsNull" SortExpression="Designation"> </telerik:GridBoundColumn> <telerik:GridEditCommandColumn> </telerik:GridEditCommandColumn> <telerik:GridButtonColumn CommandName="Delete" Text="Delete" UniqueName="column"> </telerik:GridButtonColumn> </Columns> <EditFormSettings> <FormTemplate> <table> <tr> <td>Fname*</td> <td> <asp:HiddenField ID="Fname" runat="server" Visible="false" /> <asp:TextBox ID="txtFname" runat="server" Text='<%#("Fname")%>'> </asp:TextBox> <asp:RequiredFieldValidator ID="EvalFname" ControlToValidate="txtFname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update"> *</asp:RequiredFieldValidator> </td> </tr> <tr> <td>Lname*</td> <td> <asp:HiddenField ID="HiddenField1" runat="server" Visible="false" /> <asp:TextBox ID="txtLname" runat="server" Text='<%#("Lname")%>'> </asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtLname" ErrorMessage="Enter Name" runat="server" ValidationGroup="Update"> *</asp:RequiredFieldValidator> </td> </tr> <tr> <td>Designation* </td> <td> <asp:HiddenField ID="HiddenField2" runat="server" Visible="false" /> <asp:TextBox ID="txtDesignation" runat="server" Text='<%#("Designation")%>'> </asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtDesignation" ErrorMessage="Enter Designation" runat="server" ValidationGroup="Update"> *</asp:RequiredFieldValidator> </td> </tr> </table> </FormTemplate> <EditColumn UpdateText="Update record" UniqueName="EditCommandColumn1" CancelText="Cancel edit"> </EditColumn> </EditFormSettings> </MasterTableView> </telerik:RadGrid> </form> this is my code i want to perform validation using the required validators but i think m missing smthin so pls help, here's my code behind using System; using System.Data; using System.Configuration; using System.Collections; 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.Data.SqlClient; using Telerik.Web.UI; public partial class Default7 : System.Web.UI.Page { string strQry; public SqlDataAdapter da; public DataSet ds; public SqlCommand cmd; public DataTable dt; string strCon = "Data Source=MINETDEVDATA; Initial Catalog=ML_SuppliersProd; User Id=sa; Password=@MinetApps7;"; public SqlConnection con; protected void Page_Load(object sender, EventArgs e) { } protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e) { dt = new DataTable(); con = new SqlConnection(strCon); da = new SqlDataAdapter(); try { strQry = "SELECT * FROM table2"; con.Open(); da.SelectCommand = new SqlCommand(strQry,con); da.Fill(dt); RadGrid1.DataSource = dt; } finally { con.Close(); } } protected void RadGrid1_DeleteCommand(object source, Telerik.Web.UI.GridCommandEventArgs e) { con = new SqlConnection(strCon); cmd = new SqlCommand(); GridDataItem item = (GridDataItem)e.Item; string pid = item.OwnerTableView.DataKeyValues[item.ItemIndex]["pid"].ToString(); con.Open(); string delete = "DELETE from table2 where pid='"+pid+"'"; cmd.CommandText = delete; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); } protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e) { GridEditableItem radgriditem = e.Item as GridEditableItem; string pid = radgriditem.OwnerTableView.DataKeyValues[radgriditem.ItemIndex]["pid"].ToString(); string firstname = (radgriditem["Fname"].Controls[0] as TextBox).Text; string lastname = (radgriditem["Lname"].Controls[0] as TextBox).Text; string designation = (radgriditem["Designation"].Controls[0] as TextBox).Text; con = new SqlConnection(strCon); cmd = new SqlCommand(); try { con.Open(); string update = "UPDATE table2 set Fname='" + firstname + "',Lname='" + lastname + "',Designation='" + designation + "' WHERE pid='" + pid + "'"; cmd.CommandText = update; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); } catch (Exception ex) { RadGrid1.Controls.Add(new LiteralControl("Unable to update Reason: " + ex.Message)); e.Canceled = true; } } protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e) { GridEditFormInsertItem insertitem = (GridEditFormInsertItem)e.Item; string firstname = (insertitem["Fname"].Controls[0] as TextBox).Text; string lastname = (insertitem["Lname"].Controls[0] as TextBox).Text; string designation = (insertitem["Designation"].Controls[0] as TextBox).Text; con = new SqlConnection(strCon); cmd = new SqlCommand(); try { con.Open(); String insertQuery = "INSERT into table1(Fname,Lname,Designation) Values ('" + firstname + "','" + lastname + "','" + designation + "')"; cmd.CommandText = insertQuery; cmd.Connection = con; cmd.ExecuteNonQuery(); con.Close(); } catch(Exception ex) { RadGrid1.Controls.Add(new LiteralControl("Unable to insert Reason:" + ex.Message)); e.Canceled = true; } } }

    Read the article

  • Gridview Datasource Server error

    - by salvationishere
    I am developing a C# VS 2008 and SQL Server 2008 website. However, I get the below error now when I first run this: The DataSourceID of 'GridView1' must be the ID of a control of type IDataSource. A control with ID 'AdventureWorks3.mdf' could not be found What is causing this error? Here is my default.aspx file. I have configured GridView1 to use my AdventureWorks3.mdf file, stored in my App_Data folder. Do I need to add this folder name to this ASPX file? <%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server"> <asp:Panel runat="server" ID="AuthenticatedMessagePanel"> <asp:Label runat="server" ID="WelcomeBackMessage"></asp:Label> <table> <tr > <td> <asp:Label ID="tableLabel" runat="server" Font-Bold="True" Text="Select target table:"></asp:Label> </td> <td> <asp:Label ID="inputLabel" runat="server" Font-Bold="True" Text="Select input file:"></asp:Label> </td></tr> <tr><td valign="top"> <asp:Label ID="feedbackLabel" runat="server"></asp:Label> <asp:GridView ID="GridView1" runat="server" style="WIDTH: 400px;" CellPadding="4" ForeColor="#333333" GridLines="None" onselectedindexchanged="GridView1_SelectedIndexChanged" AutoGenerateSelectButton="True" DataSourceID="AdventureWorks3.mdf" > <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> <EditRowStyle BackColor="#999999" /> <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> </asp:GridView> </td> <td valign="top"> <input id="uploadFile" type="file" size="26" runat="server" name="uploadFile" title="UploadFile" class="greybar" enableviewstate="True" /> </td></tr> </table> </asp:Panel> <asp:Panel runat="Server" ID="AnonymousMessagePanel"> <asp:HyperLink runat="server" ID="lnkLogin" Text="Log In" NavigateUrl="~/Login.aspx"> </asp:HyperLink> </asp:Panel> </asp:Content> Or what about my ASPX.CS file? Is this the problem? using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Collections.Generic; using System.IO; using System.Drawing; using System.ComponentModel; using System.Data.SqlClient; using ADONET_namespace; using System.Security.Principal; //using System.Windows; public partial class _Default : System.Web.UI.Page //namespace AddFileToSQL { //protected System.Web.UI.HtmlControls.HtmlInputFile uploadFile; protected System.Web.UI.HtmlControls.HtmlInputButton btnOWrite; protected System.Web.UI.HtmlControls.HtmlInputButton btnAppend; protected System.Web.UI.WebControls.Label Label1; protected static string inputfile = ""; public static string targettable; public static string selection; // Number of controls added to view state protected int default_NumberOfControls { get { if (ViewState["default_NumberOfControls"] != null) { return (int)ViewState["default_NumberOfControls"]; } else { return 0; } } set { ViewState["default_NumberOfControls"] = value; } } protected void uploadFile_onclick(object sender, EventArgs e) { } protected void Load_GridData() { GridView1.DataSource = ADONET_methods.DisplaySchemaTables(); GridView1.DataBind(); } protected void btnOWrite_Click(object sender, EventArgs e) { if (uploadFile.PostedFile.ContentLength > 0) { feedbackLabel.Text = "You do not have sufficient access to overwrite table records."; } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void btnAppend_Click(object sender, EventArgs e) { string fullpath = Page.Request.PhysicalApplicationPath; string path = uploadFile.PostedFile.FileName; if (File.Exists(path)) { // Create a file to write to. try { StreamReader sr = new StreamReader(path); string s = ""; while (sr.Peek() > 0) s = sr.ReadLine(); sr.Close(); } catch (IOException exc) { Console.WriteLine(exc.Message + "Cannot open file."); return; } } if (uploadFile.PostedFile.ContentLength > 0) { inputfile = System.IO.File.ReadAllText(path); Session["Message"] = inputfile; Response.Redirect("DataMatch.aspx"); } else { feedbackLabel.Text = "This file does not contain any data."; } } protected void Page_Load(object sender, EventArgs e) { if (Request.IsAuthenticated) { WelcomeBackMessage.Text = "Welcome back, " + User.Identity.Name + "!"; // Reference the CustomPrincipal / CustomIdentity CustomIdentity ident = User.Identity as CustomIdentity; if (ident != null) WelcomeBackMessage.Text += string.Format(" You are the {0} of {1}.", ident.Title, ident.CompanyName); AuthenticatedMessagePanel.Visible = true; AnonymousMessagePanel.Visible = false; //if (!Page.IsPostBack) //{ // Load_GridData(); //} } else { AuthenticatedMessagePanel.Visible = false; AnonymousMessagePanel.Visible = true; } } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; targettable = row.Cells[2].Text; } }

    Read the article

  • Ajax Control Toolkit December 2013 Release

    - by Stephen.Walther
    Today, we released a new version of the Ajax Control Toolkit that contains several important bug fixes and new features. The new release contains a new Tabs control that has been entirely rewritten in jQuery. You can download the December 2013 release of the Ajax Control Toolkit at http://Ajax.CodePlex.com. Alternatively, you can install the latest version directly from NuGet: The Ajax Control Toolkit and jQuery The Ajax Control Toolkit now contains two controls written with jQuery: the ToggleButton control and the Tabs control.  The goal is to rewrite the Ajax Control Toolkit to use jQuery instead of the Microsoft Ajax Library gradually over time. The motivation for rewriting the controls in the Ajax Control Toolkit to use jQuery is to modernize the toolkit. We want to continue to accept new controls written for the Ajax Control Toolkit contributed by the community. The community wants to use jQuery. We want to make it easy for the community to submit bug fixes. The community understands jQuery. Using the Ajax Control Toolkit with a Website that Already uses jQuery But what if you are already using jQuery in your website?  Will adding the Ajax Control Toolkit to your website break your existing website?  No, and here is why. The Ajax Control Toolkit uses jQuery.noConflict() to avoid conflicting with an existing version of jQuery in a page.  The version of jQuery that the Ajax Control Toolkit uses is represented by a variable named actJQuery.  You can use actJQuery side-by-side with an existing version of jQuery in a page without conflict.Imagine, for example, that you add jQuery to an ASP.NET page using a <script> tag like this: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TestACTDec2013.WebForm1" %> <!DOCTYPE html> <html > <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <script src="Scripts/jquery-2.0.3.min.js"></script> <ajaxToolkit:ToolkitScriptManager runat="server" /> <ajaxToolkit:TabContainer runat="server"> <ajaxToolkit:TabPanel runat="server"> <HeaderTemplate> Tab 1 </HeaderTemplate> <ContentTemplate> <h1>First Tab</h1> </ContentTemplate> </ajaxToolkit:TabPanel> <ajaxToolkit:TabPanel runat="server"> <HeaderTemplate> Tab 2 </HeaderTemplate> <ContentTemplate> <h1>Second Tab</h1> </ContentTemplate> </ajaxToolkit:TabPanel> </ajaxToolkit:TabContainer> </div> </form> </body> </html> The page above uses the Ajax Control Toolkit Tabs control (TabContainer and TabPanel controls).  The Tabs control uses the version of jQuery that is currently bundled with the Ajax Control Toolkit (jQuery version 1.9.1). The page above also includes a <script> tag that references jQuery version 2.0.3.  You might need that particular version of jQuery, for example, to use a particular jQuery plugin. The two versions of jQuery in the page do not create a conflict. This fact can be demonstrated by entering the following two commands in the JavaScript console window: actJQuery.fn.jquery $.fn.jquery Typing actJQuery.fn.jquery will display the version of jQuery used by the Ajax Control Toolkit and typing $.fn.jquery (or jQuery.fn.jquery) will show the version of jQuery used by other jQuery plugins in the page.      Preventing jQuery from Loading Twice So by default, the Ajax Control Toolkit will not conflict with any existing version of jQuery used in your application. However, this does mean that if you are already using jQuery in your application then jQuery will be loaded twice. For performance reasons, you might want to avoid loading the jQuery library twice. By taking advantage of the <remove> element in the AjaxControlToolkit.config file, you can prevent the Ajax Control Toolkit from loading its version of jQuery. <ajaxControlToolkit> <scripts> <remove name="jQuery.jQuery.js" /> </scripts> <controlBundles> <controlBundle> <control name="TabContainer" /> <control name="TabPanel" /> </controlBundle> </controlBundles> </ajaxControlToolkit> Be careful here:  the name of the script being removed – jQuery.jQuery.js – is case-sensitive. If you remove jQuery then it is your responsibility to add the exact same version of jQuery back into your application.  You can add jQuery back using a <script> tag like this: <script src="Scripts/jquery-1.9.1.min.js"></script>     Make sure that you add the <script> tag before the server-side <form> tag or the Ajax Control Toolkit won’t detect the presence of jQuery. Alternatively, you can use the ToolkitScriptManager like this: <ajaxToolkit:ToolkitScriptManager runat="server"> <Scripts> <asp:ScriptReference Name="jQuery.jQuery.js" /> </Scripts> </ajaxToolkit:ToolkitScriptManager> The Ajax Control Toolkit is tested against the particular version of jQuery that is bundled with the Ajax Control Toolkit. Currently, the Ajax Control Toolkit uses jQuery version 1.9.1. If you attempt to use a different version of jQuery with the Ajax Control Toolkit then you will get the exception jQuery 1.9.1 is required in your JavaScript console window: If you need to use a different version of jQuery in the same page as the Ajax Control Toolkit then you should not use the <remove> element. Instead, allow the Ajax Control Toolkit to load its version of jQuery side-by-side with the other version of jQuery. Lots of Bug Fixes As usual, we implemented several important bug fixes with this release. The bug fixes concerned the following three controls: Tabs control – In the course of rewriting the Tabs control to use jQuery, we fixed several bugs related to the Tabs control. AjaxFileUpload control – We resolved an issue concerning the AjaxFileUpload and the TMP directory. HTMLEditor control – We updated the HTMLEditor control to use the new Ajax Control Toolkit bundling and minification framework. Summary I would like to thank the Superexpert team for their hard work on this release. Many long hours of coding and testing went into making this release possible.

    Read the article

  • Adding the New HTML Editor Extender to a Web Forms Application using NuGet

    - by Stephen Walther
    The July 2011 release of the Ajax Control Toolkit includes a new, lightweight, HTML5 compatible HTML Editor extender. In this blog entry, I explain how you can take advantage of NuGet to quickly add the new HTML Editor control extender to a new or existing ASP.NET Web Forms application. Installing the Latest Version of the Ajax Control Toolkit with NuGet NuGet is a package manager. It enables you to quickly install new software directly from within Visual Studio 2010. You can use NuGet to install additional software when building any type of .NET application including ASP.NET Web Forms and ASP.NET MVC applications. If you have not already installed NuGet then you can install NuGet by navigating to the following address and clicking the giant install button: http://nuget.org/ After you install NuGet, you can add the Ajax Control Toolkit to a new or existing ASP.NET Web Forms application by selecting the Visual Studio menu option Tools, Library Package Manager, Package Manager Console: Selecting this menu option opens the Package Manager Console. You can enter the command Install-Package AjaxControlToolkit in the console to install the Ajax Control Toolkit: After you install the Ajax Control Toolkit with NuGet, your application will include an assembly reference to the AjaxControlToolkit.dll and SanitizerProviders.dll assemblies: Furthermore, your Web.config file will be updated to contain a new tag prefix for the Ajax Control Toolkit controls: <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <pages> <controls> <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /> </controls> </pages> </system.web> </configuration> The configuration file installed by NuGet adds the prefix ajaxToolkit for all of the Ajax Control Toolkit controls. You can type ajaxToolkit: in source view to get auto-complete in Source view. You can, of course, change this prefix to anything you want. Using the HTML Editor Extender After you install the Ajax Control Toolkit, you can use the HTML Editor Extender with the standard ASP.NET TextBox control to enable users to enter rich formatting such as bold, underline, italic, different fonts, and different background and foreground colors. For example, the following page can be used for entering comments. The page contains a standard ASP.NET TextBox, Button, and Label control. When you click the button, any text entered into the TextBox is displayed in the Label control. It is a pretty boring page: Let’s make this page fancier by extending the standard ASP.NET TextBox with the HTML Editor extender control: Notice that the ASP.NET TextBox now has a toolbar which includes buttons for performing various kinds of formatting. For example, you can change the size and font used for the text. You also can change the foreground and background color – and make many other formatting changes. You can customize the toolbar buttons which the HTML Editor extender displays. To learn how to customize the toolbar, see the HTML Editor Extender sample page here: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HTMLEditorExtender/HTMLEditorExtender.aspx Here’s the source code for the ASP.NET page: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Add Comments</title> </head> <body> <form id="form1" runat="server"> <div> <ajaxToolkit:ToolkitScriptManager ID="TSM1" runat="server" /> <asp:TextBox ID="txtComments" TextMode="MultiLine" Columns="50" Rows="8" Runat="server" /> <ajaxToolkit:HtmlEditorExtender ID="hee" TargetControlID="txtComments" Runat="server" /> <br /><br /> <asp:Button ID="btnSubmit" Text="Add Comment" Runat="server" onclick="btnSubmit_Click" /> <hr /> <asp:Label ID="lblComment" Runat="server" /> </div> </form> </body> </html> Notice that the page above contains 5 controls. The page contains a standard ASP.NET TextBox, Button, and Label control. However, the page also contains an Ajax Control Toolkit ToolkitScriptManager control and HtmlEditorExtender control. The HTML Editor extender control extends the standard ASP.NET TextBox control. The HTML Editor TargetID attribute points at the TextBox control. Here’s the code-behind for the page above:   using System; namespace WebApplication1 { public partial class Default : System.Web.UI.Page { protected void btnSubmit_Click(object sender, EventArgs e) { lblComment.Text = txtComments.Text; } } }   Preventing XSS/JavaScript Injection Attacks If you use an HTML Editor -- any HTML Editor -- in a public facing web page then you are opening your website up to Cross-Site Scripting (XSS) attacks. An evil hacker could submit HTML using the HTML Editor which contains JavaScript that steals private information such as other user’s passwords. Imagine, for example, that you create a web page which enables your customers to post comments about your website. Furthermore, imagine that you decide to redisplay the comments so every user can see them. In that case, a malicious user could submit JavaScript which displays a dialog asking for a user name and password. When an unsuspecting customer enters their secret password, the script could transfer the password to the hacker’s website. So how do you accept HTML content without opening your website up to JavaScript injection attacks? The Ajax Control Toolkit HTML Editor supports the Anti-XSS library. You can use the Anti-XSS library to sanitize any HTML content. The Anti-XSS library, for example, strips away all JavaScript automatically. You can download the Anti-XSS library from NuGet. Open the Package Manager Console and execute the command Install-Package AntiXSS: Adding the Anti-XSS library to your application adds two assemblies to your application named AntiXssLibrary.dll and HtmlSanitizationLibrary.dll. After you install the Anti-XSS library, you can configure the HTML Editor extender to use the Anti-XSS library your application’s web.config file: <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <sectionGroup name="system.web"> <section name="sanitizer" requirePermission="false" type="AjaxControlToolkit.Sanitizer.ProviderSanitizerSection, AjaxControlToolkit"/> </sectionGroup> </configSections> <system.web> <sanitizer defaultProvider="AntiXssSanitizerProvider"> <providers> <add name="AntiXssSanitizerProvider" type="AjaxControlToolkit.Sanitizer.AntiXssSanitizerProvider"></add> </providers> </sanitizer> <compilation debug="true" targetFramework="4.0" /> <pages> <controls> <add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" /> </controls> </pages> </system.web> </configuration> Summary In this blog entry, I described how you can quickly get started using the new HTML Editor extender – included with the July 2011 release of the Ajax Control Toolkit – by installing the Ajax Control Toolkit with NuGet. If you want to learn more about the HTML Editor then please take a look at the Ajax Control Toolkit sample site: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HTMLEditorExtender/HTMLEditorExtender.aspx

    Read the article

  • FAQ: GridView Calculation with JavaScript - Formatting and Validation

    - by Vincent Maverick Durano
    In my previous post here we've talked about how to calculate the sub-totals and grand total in GridView using JavaScript. In this post I'm going take more step further and will demonstrate how are we going to format the totals into a currency and how to validate the input that would only allow you to enter a whole number in the quantity TextBox. Here are the code blocks below: ASPX Source:   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <script type="text/javascript"> function CalculateTotals() { var gv = document.getElementById("<%= GridView1.ClientID %>"); var tb = gv.getElementsByTagName("input"); var lb = gv.getElementsByTagName("span"); var sub = 0; var total = 0; var indexQ = 1; var indexP = 0; var price = 0; for (var i = 0; i < tb.length; i++) { if (tb[i].type == "text") { ValidateNumber(tb[i]); price = lb[indexP].innerHTML.replace("$", "").replace(",", ""); sub = parseFloat(price) * parseFloat(tb[i].value); if (isNaN(sub)) { lb[i + indexQ].innerHTML = "0.00"; sub = 0; } else { lb[i + indexQ].innerHTML = FormatToMoney(sub, "$", ",", "."); ; } indexQ++; indexP = indexP + 2; total += parseFloat(sub); } } lb[lb.length - 1].innerHTML = FormatToMoney(total, "$", ",", "."); } function ValidateNumber(o) { if (o.value.length > 0) { o.value = o.value.replace(/[^\d]+/g, ''); //Allow only whole numbers } } function isThousands(position) { if (Math.floor(position / 3) * 3 == position) return true; return false; }; function FormatToMoney(theNumber, theCurrency, theThousands, theDecimal) { var theDecimalDigits = Math.round((theNumber * 100) - (Math.floor(theNumber) * 100)); theDecimalDigits = "" + (theDecimalDigits + "0").substring(0, 2); theNumber = "" + Math.floor(theNumber); var theOutput = theCurrency; for (x = 0; x < theNumber.length; x++) { theOutput += theNumber.substring(x, x + 1); if (isThousands(theNumber.length - x - 1) && (theNumber.length - x - 1 != 0)) { theOutput += theThousands; }; }; theOutput += theDecimal + theDecimalDigits; return theOutput; } </script> </head> <body> <form id="form1" runat="server"> <asp:gridview ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> <asp:BoundField DataField="Description" HeaderText="Item Description" /> <asp:TemplateField HeaderText="Item Price"> <ItemTemplate> <asp:Label ID="LBLPrice" runat="server" Text='<%# Eval("Price","{0:C}") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Quantity"> <ItemTemplate> <asp:TextBox ID="TXTQty" runat="server" onkeyup="CalculateTotals();"></asp:TextBox> </ItemTemplate> <FooterTemplate> <b>Total Amount:</b> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Sub-Total"> <ItemTemplate> <asp:Label ID="LBLSubTotal" runat="server" ForeColor="Green" Text="0.00"></asp:Label> </ItemTemplate> <FooterTemplate> <asp:Label ID="LBLTotal" runat="server" ForeColor="Green" Font-Bold="true" Text="0.00"></asp:Label> </FooterTemplate> </asp:TemplateField> </Columns> </asp:gridview> </form> </body> </html> Code Behind Source:   public partial class GridCalculation : System.Web.UI.Page { private void BindDummyDataToGrid() { DataTable dt = new DataTable(); DataRow dr = null; dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); dt.Columns.Add(new DataColumn("Description", typeof(string))); dt.Columns.Add(new DataColumn("Price", typeof(decimal))); dr = dt.NewRow(); dr["RowNumber"] = 1; dr["Description"] = "Nike"; dr["Price"] = "1000"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 2; dr["Description"] = "Converse"; dr["Price"] = "800"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 3; dr["Description"] = "Adidas"; dr["Price"] = "500"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 4; dr["Description"] = "Reebok"; dr["Price"] = "750"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 5; dr["Description"] = "Vans"; dr["Price"] = "1100"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 6; dr["Description"] = "Fila"; dr["Price"] = "200"; dt.Rows.Add(dr); //Bind the Gridview GridView1.DataSource = dt; GridView1.DataBind(); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindDummyDataToGrid(); } } } Running the code above will display something like this: On initial load After entering the quantity in the TextBox That's it! I hope someone find this post useful! Technorati Tags: ASP.NET,C#,ADO.NET,JavaScript,GridView

    Read the article

  • Using Radio Button in GridView with Validation

    - by Vincent Maverick Durano
    A developer is asking how to select one radio button at a time if the radio button is inside the GridView.  As you may know setting the group name attribute of radio button will not work if the radio button is located within a Data Representation control like GridView. This because the radio button inside the gridview bahaves differentely. Since a gridview is rendered as table element , at run time it will assign different "name" to each radio button. Hence you are able to select multiple rows. In this post I'm going to demonstrate how select one radio button at a time in gridview and add a simple validation on it. To get started let's go ahead and fire up visual studio and the create a new web application / website project. Add a WebForm and then add gridview. The mark up would look something like this: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" > <Columns> <asp:TemplateField> <ItemTemplate> <asp:RadioButton ID="rb" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> <asp:BoundField DataField="Col1" HeaderText="First Column" /> <asp:BoundField DataField="Col2" HeaderText="Second Column" /> </Columns> </asp:GridView> Noticed that I've added a templatefield column so that we can add the radio button there. Also I have set up some BoundField columns and set the DataFields as RowNumber, Col1 and Col2. These columns are just dummy columns and i used it for the simplicity of this example. Now where these columns came from? These columns are created by hand at the code behind file of the ASPX. Here's the code below: private DataTable FillData() { DataTable dt = new DataTable(); DataRow dr = null; //Create DataTable columns dt.Columns.Add(new DataColumn("RowNumber", typeof(string))); dt.Columns.Add(new DataColumn("Col1", typeof(string))); dt.Columns.Add(new DataColumn("Col2", typeof(string))); //Create Row for each columns dr = dt.NewRow(); dr["RowNumber"] = 1; dr["Col1"] = "A"; dr["Col2"] = "B"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 2; dr["Col1"] = "AA"; dr["Col2"] = "BB"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 3; dr["Col1"] = "A"; dr["Col2"] = "B"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 4; dr["Col1"] = "A"; dr["Col2"] = "B"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["RowNumber"] = 5; dr["Col1"] = "A"; dr["Col2"] = "B"; dt.Rows.Add(dr); return dt; } And here's the code for binding the GridView with the dummy data above. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView1.DataSource = FillData(); GridView1.DataBind(); } } Okay we have now a GridView data with a radio button on each row. Now lets go ahead and switch back to ASPX mark up. In this example I'm going to use a JavaScript for validating the radio button to select one radio button at a time. Here's the javascript code below: function CheckOtherIsCheckedByGVID(rb) { var isChecked = rb.checked; var row = rb.parentNode.parentNode; if (isChecked) { row.style.backgroundColor = '#B6C4DE'; row.style.color = 'black'; } var currentRdbID = rb.id; parent = document.getElementById("<%= GridView1.ClientID %>"); var items = parent.getElementsByTagName('input'); for (i = 0; i < items.length; i++) { if (items[i].id != currentRdbID && items[i].type == "radio") { if (items[i].checked) { items[i].checked = false; items[i].parentNode.parentNode.style.backgroundColor = 'white'; items[i].parentNode.parentNode.style.color = '#696969'; } } } } The function above sets the row of the current selected radio button's style to determine that the row is selected and then loops through the radio buttons in the gridview and then de-select the previous selected radio button and set the row style back to its default. You can then call the javascript function above at onlick event of radio button like below: <asp:RadioButton ID="rb" runat="server" onclick="javascript:CheckOtherIsCheckedByGVID(this);" /> Here's the output below: On Load: After Selecting a Radio Button: As you have noticed, on initial load there's no default selected radio in the GridView. Now let's add a simple validation for that. We will basically display an error message if a user clicks a button that triggers a postback without selecting  a radio button in the GridView. Here's the javascript for the validation: function ValidateRadioButton(sender, args) { var gv = document.getElementById("<%= GridView1.ClientID %>"); var items = gv.getElementsByTagName('input'); for (var i = 0; i < items.length ; i++) { if (items[i].type == "radio") { if (items[i].checked) { args.IsValid = true; return; } else { args.IsValid = false; } } } } The function above loops through the rows in gridview and find all the radio buttons within it. It will then check each radio button checked property. If a radio is checked then set IsValid to true else set it to false.  The reason why I'm using IsValid is because I'm using the ASP validator control for validation. Now add the following mark up below under the GridView declaration: <br /> <asp:Label ID="lblMessage" runat="server" /> <br /> <asp:Button ID="btn" runat="server" Text="POST" onclick="btn_Click" ValidationGroup="GroupA" /> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select row in the grid." ClientValidationFunction="ValidateRadioButton" ValidationGroup="GroupA" style="display:none"></asp:CustomValidator> <asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="GroupA" HeaderText="Error List:" DisplayMode="BulletList" ForeColor="Red" /> And then at Button Click event add this simple code below just to test if  the validation works: protected void btn_Click(object sender, EventArgs e) { lblMessage.Text = "Postback at: " + DateTime.Now.ToString("hh:mm:ss tt"); } Here's the output below that you can see in the browser:   That's it! I hope someone find this post useful! Technorati Tags: ASP.NET,JavaScript,GridView

    Read the article

  • Find CheckBox from GridView in Content Page/Master Page

    - by Suthish Nair
    How to find a control from GridView which resides in Content Page Here the example using to find the CheckBox, hope this will help you all... .aspx code <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> <asp:GridView ID="GridView1" runat="server"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="chkID" runat="server" /> </ItemTemplate> </asp...(read more)

    Read the article

  • How to create dynamically LinkButton with Literal Control in ASP.NET

    - by SAMIR BHOGAYTA
    Step 1 : First take following control into the .aspx page. asp:UpdatePanel id="up1" runat="server" contenttemplate asp:Literal ID="lt1" Text="" runat="server" asp:PlaceHolder ID="ph1" runat="server" /asp:PlaceHolder /contenttemplate /asp:UpdatePanel Step 2 : string query = query for fill the dataset; DataSet ds = new DataSet(); ds = pass the query to retrive data; int i = 0; LinkButton lt = new LinkButton(); for (i = 0; i { lt = new LinkButton(); lt.ID = "link" + i.ToString(); lt.Text = ds.Tables[0].Rows[i].ItemArray[1].ToString(); ph1.Controls.Add(lt); ph1.Controls.Add(new LiteralControl(" ")); }

    Read the article

  • Making your ASP.NET/HTML Websites Indic aware &ndash; accepting Tamil, Telugu, Kannada, Hindi and ot

    - by Harish Ranganathan
    Its been a month since I wrote my last post.  Much of work has been happening around planning for Tech Ed India, the upcoming Virtual TechDays this week as well as our Developer content at the Great Indian Developer Summit 2010.  Its going to be one exciting period starting this week and I am glad I would be able to meet a lot of folks who have written to me personally that they would like to catch up at Tech Ed India. For now, I had a chance to meet the Microsoft India Development Centre team that worked on the Microsoft Indic Language Input Tool (erstwhile Akshara). The team updated me that they have also released the scripts  so that the Indic input feature can be encapsulated into your own websites.  For example, if you are having a web page where you collect user information, you can pretty much make your site indic aware i.e. accept inputs in Tamil, Telugu, Kannada, Hindi etc.,  All you would need to include would be a bunch of scripts onto your web pages and you are ready to make it, like I said, “indic aware” I have built a sample web page that accepts First Name, Last Name, Address and an additional field.  When it comes to accepting indic, sometimes, you may want to avoid the indic input in certain fields and accept it in English.  You can specify the MicrosoftILITWebAttach="false" attribute to the Text Boxes and Text Areas (TextMode=”Multiline” in ASP.NET) so that the particular field automatically switches over to English input.  Similarly, the moment you specify that the TextMode=”Password” to make it as a password field, it automatically ignores all indic recognition and shows the masked dots for the words entered. Note that, this is, when we are going for the Opt-out mode, where we are specifying that by default all the input controls would need indic awareness and we would specify for those controls where it is not required.  The other mode is Opt-in mode where you would need to add a different property to the script definition i.e. attachMode=”optin” .  When we do this, we need to explicitly add the MicrosoftILITWebAttach="true" attribute for every control where we need indic input. I have created a sample web page which accepts First Name, Last Name, Address and an additional input field to demonstrate the “Opt-out”.   You can copy paste this into any of your web pages to check it <form id="form1" runat="server">     <!-- Microsoft Indic Language Input Tool embed code --> <input type="hidden" id="MicrosoftILITWebEmbedInfo" attachMode="optout" value="" /> <script type="text/javascript" src="http://ilit.microsoft.com/bookmarklet/script/Tamil.js" defer="defer"></script>     <div>     <h2>         Welcome to the Registration Page     </h2>     <p>         First Name: <asp:TextBox runat="server" ID="txtFirstName" />         <br />         <br />         Last Name: <asp:TextBox runat="server" ID="txtLastName" />         <br />         <br />         Password:         <asp:TextBox runat="server" ID="txtPassword" TextMode="Password" />         <br />         <br />         Address: <asp:TextBox runat="server" ID="txtAddress" TextMode="MultiLine" Height="100" Width="200" />         <br />         <br />         English Text: <asp:TextBox ID="txtEnglishText" runat="server" MicrosoftILITWebAttach="false" />     </p>     <p>         <!-- Microsoft Indic Language Input Tool attribution image link --> <a style="text-decoration: none" href="http://go.microsoft.com/fwlink/?LinkID=184205&clcid=0x409"><img style="border: 0px" alt="Transliteration by Microsoft" src="http://ilit.microsoft.com/bookmarklet/images/attribution.png"></a>     </p>     </div>     </form> If you note the code snippet above, I have included the scripts in the top with the attachMode set to “optout” and for the last TextBox, I have mentioned the MicrosoftILITWebAttach="false” attribute to make it accept English input.   Additionally, you also need to add the “Microsoft Indic Language Input Tool attribution image” to your web page as a courtesy to the team that developed this feature.  It would basically add a image saying “Transliteration by Microsoft” similar to a Copy Right image.  You can see the screen shot below where I have typed it in Tamil.  In that you will notice that the password field behaves as expected and the last field accepts English Text.  You can also notice the icon that comes in the first textbox that indicates that, the field is going to accept indic text.   This sample is using Tamil, but you can pretty much do it for Hindi, Telugu, Kannada, Marathi, Bengali etc.,   The website for getting the Indic script and other instructions is http://specials.msn.co.in/ilit/WebEmbed.aspx?language=Tamil You can replace the querystring value “Tamil” to other languages as mentioned above to get the respective script. This also works for plain HTML based websites and doesn’t necessarily need you to use ASP.NET to achieve the functionality. Note that, this form is not completely localized.  This is transliterated.  You can add label controls for FirstName, LastName indication etc., and use the Visual Studio tools to localize and get those values from resource files.  In the resource files, you can enter the text in different languages to make this a truly localized page.  If you just want to download the Indic Tool Desktop version (that can be used for typing in Word, Excel, pretty much any input area), you can download it from http://specials.msn.co.in/ilit/  In the same page, there is also a web version where you can type and get text then and there if you dont want to install the desktop version. So, go ahead, download / use them in your websites and enjoy the power of Indic. Cheers !!!

    Read the article

  • Alternative way of developing for ASP.NET to WebForms - Any problems with this?

    - by John
    So I have been developing in ASP.NET WebForms for some time now but often get annoyed with all the overhead (like ViewState and all the JavaScript it generates), and the way WebForms takes over a lot of the HTML generation. Sometimes I just want full control over the markup and produce efficient HTML of my own so I have been experimenting with what I like to call HtmlForms. Essentially this is using ASP.NET WebForms but without the form runat="server" tag. Without this tag, ASP.NET does not seem to add anything to the page at all. From some basic tests it seems that it runs well and you still have the ability to use code-behind pages, and many ASP.NET controls such as repeaters. Of course without the form runat="server" many controls won't work. A post at Enterprise Software Development lists the controls that do require the tag. From that list you will see that all of the form elements like TextBoxes, DropDownLists, RadioButtons, etc cannot be used. Instead you use normal HTML form controls. But how do you access these HTML controls from the code behind? Retrieving values on post back is easy, you just use Request.QueryString or Request.Form. But passing data to the control could be a little messy. Do you use a ASP.NET Literal control in the value field or do you use <%= value % in the markup page? I found it best to add runat="server" to my HTML controls and then you can access the control in your code-behind like this: ((HtmlInputText)txtName).Value = "blah"; Here's a example that shows what you can do with a textbox and drop down list: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="NoForm.Default" %> <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="NoForm.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form action="" method="post"> <label for="txtName">Name:</label> <input id="txtName" name="txtName" runat="server" /><br /> <label for="ddlState">State:</label> <select id="ddlState" name="ddlState" runat="server"> <option value=""></option> </select><br /> <input type="submit" value="Submit" /> </form> </body> </html> Default.aspx.cs using System; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace NoForm { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Default values string name = string.Empty; string state = string.Empty; if (Request.RequestType == "POST") { //If form submitted (post back) name = Request.Form["txtName"]; state = Request.Form["ddlState"]; //Server side form validation would go here //and actions to process form and redirect } ((HtmlInputText)txtName).Value = name; ((HtmlSelect)ddlState).Items.Add(new ListItem("ACT")); ((HtmlSelect)ddlState).Items.Add(new ListItem("NSW")); ((HtmlSelect)ddlState).Items.Add(new ListItem("NT")); ((HtmlSelect)ddlState).Items.Add(new ListItem("QLD")); ((HtmlSelect)ddlState).Items.Add(new ListItem("SA")); ((HtmlSelect)ddlState).Items.Add(new ListItem("TAS")); ((HtmlSelect)ddlState).Items.Add(new ListItem("VIC")); ((HtmlSelect)ddlState).Items.Add(new ListItem("WA")); if (((HtmlSelect)ddlState).Items.FindByValue(state) != null) ((HtmlSelect)ddlState).Value = state; } } } As you can see, you have similar functionality to ASP.NET server controls but more control over the final markup, and less overhead like ViewState and all the JavaScript ASP.NET adds. Interestingly you can also use HttpPostedFile to handle file uploads using your own input type="file" control (and necessary form enctype="multipart/form-data"). So my question is can you see any problems with this method, and any thoughts on it's usefulness? I have further details and tests on my blog.

    Read the article

  • More SharePoint 2010 Expression Builders

    - by Ricardo Peres
    Introduction Following my last post, I decided to publish the whole set of expression builders that I use with SharePoint. For all who don’t know about expression builders, they allow us to employ a declarative approach, so that we don’t have to write code for “gluing” things together, like getting a value from the query string, the page’s underlying SPListItem or the current SPContext and assigning it to a control’s property. These expression builders are for some quite common scenarios, I use them quite often, and I hope you find them useful as well. SPContextExpression This expression builder allows us to specify an expression to be processed on the SPContext.Current property object. For example: 1: <asp:Literal runat="server" Text=“<%$ SPContextExpression:Site.RootWeb.Lists[0].Author.LoginName %>”/> It is identical to having the following code: 1: String authorName = SPContext.Current.Site.RootWeb.Lists[0].Author.LoginName; SPFarmProperty Returns a property stored on the farm level: 1: <asp:Literal runat="server" Text="<%$ SPFarmProperty:SomeProperty %>"/> Identical to: 1: Object someProperty = SPFarm.Local.Properties["SomeProperty"]; SPField Returns the value of a selected page’s list item field: 1: <asp:Literal runat="server" Text="<%$ SPField:Title %>"/> Does the same as: 1: String title = SPContext.Current.ListItem["Title"] as String; SPIsInAudience Checks if the current user belongs to an audience: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInAudience:SomeAudience %>"/> Equivalent to: 1: AudienceManager audienceManager = new AudienceManager(SPServiceContext.Current); 2: Audience audience = audienceManager.Audiences["SomeAudience"]; 3: Boolean isMember = audience.IsMember(SPContext.Current.Web.User.LoginName); SPIsInGroup Checks if the current user belongs to a group: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInGroup:SomeGroup %>"/> The equivalent C# code is: 1: SPContext.Current.Web.CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, “SomeGroup”, StringComparison.OrdinalIgnoreCase)); SPProperty Returns the value of a user profile property for the current user: 1: <asp:Literal runat="server" Text="<%$ SPProperty:LastName %>"/> Where the same code in C# would be: 1: UserProfileManager upm = new UserProfileManager(SPServiceContext.Current); 2: UserProfile u = upm.GetUserProfile(false); 3: Object property = u["LastName"].Value; SPQueryString Returns a value passed on the query string: 1: <asp:GridView runat="server" PageIndex="<%$ SPQueryString:PageIndex %>" /> Is equivalent to (no SharePoint code this time): 1: Int32 pageIndex = Convert.ChangeType(typeof(Int32), HttpContext.Current.Request.QueryString["PageIndex"]); SPWebProperty Returns the value of a property stored at the site level: 1: <asp:Literal runat="server" Text="<%$ SPWebProperty:__ImagesListId %>"/> You can get the same result as: 1: String imagesListId = SPContext.Current.Web.AllProperties["__ImagesListId"] as String; Code OK, let’s move to the code. First, a common abstract base class, mainly for inheriting the conversion method: 1: public abstract class SPBaseExpressionBuilder : ExpressionBuilder 2: { 3: #region Protected static methods 4: protected static Object Convert(Object value, PropertyInfo propertyInfo) 5: { 6: if (value != null) 7: { 8: if (propertyInfo.PropertyType.IsAssignableFrom(value.GetType()) == false) 9: { 10: if (propertyInfo.PropertyType.IsEnum == true) 11: { 12: value = Enum.Parse(propertyInfo.PropertyType, value.ToString(), true); 13: } 14: else if (propertyInfo.PropertyType == typeof(String)) 15: { 16: value = value.ToString(); 17: } 18: else if ((typeof(IConvertible).IsAssignableFrom(propertyInfo.PropertyType) == true) && (typeof(IConvertible).IsAssignableFrom(value.GetType()) == true)) 19: { 20: value = System.Convert.ChangeType(value, propertyInfo.PropertyType); 21: } 22: } 23: } 24:  25: return (value); 26: } 27: #endregion 28:  29: #region Public override methods 30: public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 31: { 32: if (String.IsNullOrEmpty(entry.Expression) == true) 33: { 34: return (new CodePrimitiveExpression(String.Empty)); 35: } 36: else 37: { 38: return (new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(this.GetType()), "GetValue"), new CodePrimitiveExpression(entry.Expression.Trim()), new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("entry"), "PropertyInfo"))); 39: } 40: } 41: #endregion 42:  43: #region Public override properties 44: public override Boolean SupportsEvaluate 45: { 46: get 47: { 48: return (true); 49: } 50: } 51: #endregion 52: } Next, the code for each expression builder: 1: [ExpressionPrefix("SPContext")] 2: public class SPContextExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String expression, PropertyInfo propertyInfo) 6: { 7: SPContext context = SPContext.Current; 8: Object expressionValue = DataBinder.Eval(context, expression.Trim().Replace('\'', '"')); 9:  10: expressionValue = Convert(expressionValue, propertyInfo); 11:  12: return (expressionValue); 13: } 14:  15: #endregion 16:  17: #region Public override methods 18: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 19: { 20: return (GetValue(entry.Expression, entry.PropertyInfo)); 21: } 22: #endregion 23: }   1: [ExpressionPrefix("SPFarmProperty")] 2: public class SPFarmPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPFarm.Local.Properties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPField")] 2: public class SPFieldExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String fieldName, PropertyInfo propertyInfo) 6: { 7: Object fieldValue = SPContext.Current.ListItem[fieldName]; 8:  9: fieldValue = Convert(fieldValue, propertyInfo); 10:  11: return (fieldValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPIsInAudience")] 2: public class SPIsInAudienceExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String audienceName, PropertyInfo info) 6: { 7: Debugger.Break(); 8: audienceName = audienceName.Trim(); 9:  10: if ((audienceName.StartsWith("'") == true) && (audienceName.EndsWith("'") == true)) 11: { 12: audienceName = audienceName.Substring(1, audienceName.Length - 2); 13: } 14:  15: AudienceManager manager = new AudienceManager(); 16: Object value = manager.IsMemberOfAudience(SPControl.GetContextWeb(HttpContext.Current).CurrentUser.LoginName, audienceName); 17:  18: if (info.PropertyType == typeof(String)) 19: { 20: value = value.ToString(); 21: } 22:  23: return(value); 24: } 25:  26: #endregion 27:  28: #region Public override methods 29: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 30: { 31: return (GetValue(entry.Expression, entry.PropertyInfo)); 32: } 33: #endregion 34: }   1: [ExpressionPrefix("SPIsInGroup")] 2: public class SPIsInGroupExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String groupName, PropertyInfo info) 6: { 7: groupName = groupName.Trim(); 8:  9: if ((groupName.StartsWith("'") == true) && (groupName.EndsWith("'") == true)) 10: { 11: groupName = groupName.Substring(1, groupName.Length - 2); 12: } 13:  14: Object value = SPControl.GetContextWeb(HttpContext.Current).CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, groupName, StringComparison.OrdinalIgnoreCase)); 15:  16: if (info.PropertyType == typeof(String)) 17: { 18: value = value.ToString(); 19: } 20:  21: return(value); 22: } 23:  24: #endregion 25:  26: #region Public override methods 27: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 28: { 29: return (GetValue(entry.Expression, entry.PropertyInfo)); 30: } 31: #endregion 32: }   1: [ExpressionPrefix("SPProperty")] 2: public class SPPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, System.Reflection.PropertyInfo propertyInfo) 6: { 7: SPServiceContext serviceContext = SPServiceContext.GetContext(HttpContext.Current); 8: UserProfileManager upm = new UserProfileManager(serviceContext); 9: UserProfile up = upm.GetUserProfile(false); 10: Object propertyValue = (up[propertyName] != null) ? up[propertyName].Value : null; 11:  12: propertyValue = Convert(propertyValue, propertyInfo); 13:  14: return (propertyValue); 15: } 16:  17: #endregion 18:  19: #region Public override methods 20: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 21: { 22: return (GetValue(entry.Expression, entry.PropertyInfo)); 23: } 24: #endregion 25: }   1: [ExpressionPrefix("SPQueryString")] 2: public class SPQueryStringExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String parameterName, PropertyInfo propertyInfo) 6: { 7: Object parameterValue = HttpContext.Current.Request.QueryString[parameterName]; 8:  9: parameterValue = Convert(parameterValue, propertyInfo); 10:  11: return (parameterValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPWebProperty")] 2: public class SPWebPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPContext.Current.Web.AllProperties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: } Registration You probably know how to register them, but here it goes again: add this following snippet to your Web.config file, inside the configuration/system.web/compilation/expressionBuilders section: 1: <add expressionPrefix="SPContext" type="MyNamespace.SPContextExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 2: <add expressionPrefix="SPFarmProperty" type="MyNamespace.SPFarmPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 3: <add expressionPrefix="SPField" type="MyNamespace.SPFieldExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 4: <add expressionPrefix="SPIsInAudience" type="MyNamespace.SPIsInAudienceExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 5: <add expressionPrefix="SPIsInGroup" type="MyNamespace.SPIsInGroupExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 6: <add expressionPrefix="SPProperty" type="MyNamespace.SPPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 7: <add expressionPrefix="SPQueryString" type="MyNamespace.SPQueryStringExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 8: <add expressionPrefix="SPWebProperty" type="MyNamespace.SPWebPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> I’ll leave it up to you to figure out the best way to deploy this to your server!

    Read the article

  • An Unusual UpdatePanel

    - by João Angelo
    The code you are about to see was mostly to prove a point, to myself, and probably has limited applicability. Nonetheless, in the remote possibility this is useful to someone here it goes… So this is a control that acts like a normal UpdatePanel where all child controls are registered as postback triggers except for a single control specified by the TriggerControlID property. You could basically achieve the same thing by registering all controls as postback triggers in the regular UpdatePanel. However with this, that process is performed automatically. Finally, here is the code: public sealed class SingleAsyncTriggerUpdatePanel : WebControl, INamingContainer { public string TriggerControlID { get; set; } [TemplateInstance(TemplateInstance.Single)] [PersistenceMode(PersistenceMode.InnerProperty)] public ITemplate ContentTemplate { get; set; } public override ControlCollection Controls { get { this.EnsureChildControls(); return base.Controls; } } protected override void CreateChildControls() { if (string.IsNullOrWhiteSpace(this.TriggerControlID)) throw new InvalidOperationException( "The TriggerControlId property must be set."); this.Controls.Clear(); var updatePanel = new UpdatePanel() { ID = string.Concat(this.ID, "InnerUpdatePanel"), ChildrenAsTriggers = false, UpdateMode = UpdatePanelUpdateMode.Conditional, ContentTemplate = this.ContentTemplate }; updatePanel.Triggers.Add(new SingleControlAsyncUpdatePanelTrigger { ControlID = this.TriggerControlID }); this.Controls.Add(updatePanel); } } internal sealed class SingleControlAsyncUpdatePanelTrigger : UpdatePanelControlTrigger { private Control target; private ScriptManager scriptManager; public Control Target { get { if (this.target == null) { this.target = this.FindTargetControl(true); } return this.target; } } public ScriptManager ScriptManager { get { if (this.scriptManager == null) { var page = base.Owner.Page; if (page != null) { this.scriptManager = ScriptManager.GetCurrent(page); } } return this.scriptManager; } } protected override bool HasTriggered() { string asyncPostBackSourceElementID = this.ScriptManager.AsyncPostBackSourceElementID; if (asyncPostBackSourceElementID == this.Target.UniqueID) return true; return asyncPostBackSourceElementID.StartsWith( string.Concat(this.target.UniqueID, "$"), StringComparison.Ordinal); } protected override void Initialize() { base.Initialize(); foreach (Control control in FlattenControlHierarchy(this.Owner.Controls)) { if (control == this.Target) continue; bool isApplicableControl = false; isApplicableControl |= control is INamingContainer; isApplicableControl |= control is IPostBackDataHandler; isApplicableControl |= control is IPostBackEventHandler; if (isApplicableControl) { this.ScriptManager.RegisterPostBackControl(control); } } } private static IEnumerable<Control> FlattenControlHierarchy( ControlCollection collection) { foreach (Control control in collection) { yield return control; if (control.Controls.Count > 0) { foreach (Control child in FlattenControlHierarchy(control.Controls)) { yield return child; } } } } } You can use it like this, meaning that only the B2 button will trigger an async postback: <cc:SingleAsyncTriggerUpdatePanel ID="Test" runat="server" TriggerControlID="B2"> <ContentTemplate> <asp:Button ID="B1" Text="B1" runat="server" OnClick="Button_Click" /> <asp:Button ID="B2" Text="B2" runat="server" OnClick="Button_Click" /> <asp:Button ID="B3" Text="B3" runat="server" OnClick="Button_Click" /> <asp:Label ID="LInner" Text="LInner" runat="server" /> </ContentTemplate> </cc:SingleAsyncTriggerUpdatePanel>

    Read the article

  • ASP.NET 4.0 UpdatePanel and UserControl with PlaceHolder

    - by Chris
    I don't know if this is ASP.NET 4.0 specific but I don't recall having this problem in previous versions. I have very simple user control called "TestModal" that contains a PlaceHolder control which I use to instantiate a template in. When I put an UpdatePanel inside this UserControl on the page the updatepanel only does full postbacks and not partial postbacks. What gives? USER CONTROL MARKUP: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestModal.ascx.cs" Inherits="MyProject.UserControls.TestModal" %> <div id="<%= this.ClientID %>"> <asp:PlaceHolder ID="plchContentTemplate" runat="server"></asp:PlaceHolder> </div> USER CONTROL CODE BEHIND: public partial class TestModal : System.Web.UI.UserControl { private ITemplate _contentTemplate; [TemplateInstance(TemplateInstance.Single)] [PersistenceMode(PersistenceMode.InnerProperty), TemplateContainer(typeof(TemplateControl))] public ITemplate ContentTemplate { get { return _contentTemplate; } set { _contentTemplate = value; } } protected override void OnInit(EventArgs e) { base.OnInit(e); if (_contentTemplate != null) _contentTemplate.InstantiateIn(plchContentTemplate); } } ASPX PAGE MARKUP: <ajaxToolkit:ToolkitScriptManager ID="scriptManager" EnablePartialRendering="true" AllowCustomErrorsRedirect="true" CombineScripts="true" EnablePageMethods="true" ScriptMode="Release" AsyncPostBackTimeout="180" runat="server"></ajaxToolkit:ToolkitScriptManager> <uc1:TestModal ID="testModal" ClientIDMode="Static" runat="server"> <ContentTemplate> <asp:UpdatePanel ID="upAttachments" UpdateMode="Conditional" ChildrenAsTriggers="true" runat="server"> <ContentTemplate> <asp:LinkButton ID="lnkRemoveAttachment" runat="server"><img src="/images/icons/trashcan.png" style="border: none;" /></asp:LinkButton> </ContentTemplate> </asp:UpdatePanel> </ContentTemplate> </uc1:TestModal>

    Read the article

  • Using initParams in Silverlight 4 project

    - by Silverlight Beginner
    I'm trying to upgrade a project that uses Silverlight 2 to use Silverlight 4 but I have problem with initparam to set domain. The old Silverlight 2 project: <form id="form1" runat="server" style="height:100%;"> <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <div style="height:100%;"> <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/EKAKC.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" /> </div> </form> And from Default.aspx.cs: Xaml1.InitParameters += "Domain=" + domain; The new Silverlight 4 project: <body style="height: 100%; margin: 0;"> <form id="form1" runat="server" style="height: 100%;"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div id="silverlightControlHost"> <object type="application/x-silverlight-2" data="data:application/x-silverlight," width="300" height="300"> <param name="source" value="EKAKC.xap"/> <param name="initParams" value="<%= string.Format("WCFReferenceURL={0}", ConfigurationManager.AppSettings["WCFReferenceURL"])%>" /> </object> </div> The Domain will not be set in my new Silverlight 4 project

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >