Setting UserControl properties dynamcally on Aspx page - asp.net

Im making a generic modal usercontrol that i can call on different Aspx pages and set the text via parameter. First i created 2 properties on the Codebehind of my UserControl
public partial class _modalGenerica : System.Web.UI.UserControl
{
public string Body { get; set; }
public string Title { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Than i created the modal button on my ascx and tried to access the properties
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="_modalGenerica.ascx.cs" Inherits="GS1.CNP.WEBUI.views.backoffice.areaEstatica.formularioProduto._modalGenerica" %>
<button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="<%this.Title%>" data-content="<%this.Body%>"> Click to toggle popover</button>
And lastly i call the UC on the the aspx page with this line
<partial:_modalGenerica runat="server" id="_modalGenerica" Body="Hhahaha" Title="Teste" />
The aspx page is not loading after i created the button modal, any ideas? or better solutions for this?

Related

Custom Control Event not firing inside a user control

I implement a custom control that handle post back event:
namespace CalendarControls
{
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
public class CalendarPostback : WebControl, IPostBackEventHandler
{
public delegate void CalendarPostBackHandler(object sender, CalendarPostbackEventArgs e);
public event CalendarPostBackHandler CalendarPostBack;
public CalendarPostback()
{
}
#region IPostBackEventHandler Members
public void RaisePostBackEvent(string eventArgument)
{
string[] values = eventArgument.Split('|');
CalendarPostbackEventArgs args = new CalendarPostbackEventArgs();
args.EventType = (eEventType)Convert.ToInt32(values[0]);
if (args.EventType == eEventType.Insert)
args.EventDate = Convert.ToDateTime(values[1]);
else
args.EventId = Convert.ToInt32(values[1]);
if (CalendarPostBack != null)
CalendarPostBack(this, args);
}
#endregion
}
public class CalendarPostbackEventArgs : EventArgs
{
public CalendarPostbackEventArgs()
{
}
public eEventType EventType
{
get;
set;
}
public DateTime EventDate
{
get;
set;
}
public int? EventId
{
get;
set;
}
}
}
and I use this custom control in a usercontrol ,and call it on a button click inside my usercontrol with following javascript code:
function CallPostBack(eventArguments) {
__doPostBack('<%=ctl1.ClientID %>', eventArguments);
}
and my html code in usercontrol:
<input type="button" value="Insert" onclick="CallPostBack('1|2014/06/12')" />
<CalendarControls:CalendarPostback ID="ctl1" runat="server" ClientIDMode="Static" OnCalendarPostBack="ctl1_CalendarPostBack" />
but when I click on my button, page postback occur but ctl1_CalendarPostBack event not fired. also I must to say that I add user control directly to aspx page (not dynamically) and my aspx page have a master page.
now I have two question:
what's wrong with my code? how to solve this issue?
if I want to add my custom control to an update panel and I want to have an async post back, what I must do?
thank you,
best regards
I found problem! when we use master page ,client id and unique id of control is different and we must to use unique id instead of client id:
function CallPostBack(eventArguments) {
__doPostBack('<%=ctl1.UniqueID %>', eventArguments);
}

How to Prevent Post back of Menu Control that is on Master Page in asp.net?

I have created Dynamic Menu from Database of SQLServer2008 which is loaded on page load and accordingly the menus are displayed. Problem is when i click any MenuItem of the menu from Content Page the Menu Control also loads again from the DataBase which i want to avoid the PostBack and prevent the Hit to DataBase for loading the menu.
In .master
<body>
<form runat="server">
<div class="page">
<div id="navbar" runat="server">
<asp:Menu ID="Menu1" Orientation="horizontal" RenderingMode="List" runat="server"
DynamicHorizontalOffset="0" OnMenuItemClick="Menu1_MenuItemClick">
<StaticMenuItemStyle HorizontalPadding="10px" />
</asp:Menu>
</div>
<br />
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server">
Content here....
</asp:ContentPlaceHolder>
</div>
</div>
<div class="footer">
</div>
</form>
</body>
In .master.cs file
public partial class SiteMaster : System.Web.UI.MasterPage
{
static string conStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
int empID = 0;
int recAffect = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateMenuItem();
}
}
}
populateMenuItem() is a method from where the Menu is Bind from SQLServerDB table called MenuMaster.
When i click any MenuItem the page is redirected. This works fine. Just i want to AVOID the LOADING OF MENU afte EACH LOADING OF CONTENT PAGE!
Help Appreciated!
Thanks in Advance!
What I do is once the application loads, I create the menu and load it into memory, and then query the data from memory instead. So I create a class like:
public class SiteMap
{
public string Name { get; set; }
public string Url { get; set; }
public List<SiteMap> Items { get; set; }
}
During the starting up of your application, query from database and build a collection of SiteMap objects, and store this in a static reference, like:
public static class SiteMapStore
{
private static List<SiteMap> _entries = null;
public static List<SiteMap> Entries
{
get { return _entries; }
set
{
if (_entries == value)
return;
lock(typeof(SiteMapStore))
{
if (_entries != value)
_entries = value;
}
}
}
}
Using the SiteMapStore, you can then always refer to this when building the menu. Storing the results in an object and globally will be much faster.

ASP.NET customized asp:label view state

I created a new class for a project. The below is a very slightly simplified version.
public class CustomLabel : Label
{
public string ItemId { get; set; }
protected override void Render(HtmlTextWriter writer)
{
if (!Page.IsPostBack)
LoadText();
base.Render(writer);
}
protected void LoadText()
{
this.Text = "This is a test";
}
}
The problem I'm having is that the Text property is not lasting through postbacks. Even if I manually enable viewstate though the tag on the ascx page. Can the custom label tag not have viewstate? I would hate to have to load the text on every page load unnecessarily.
Move LoadText(); method call to OnPreRender method

Reference masterpage variables from control in child page?

Is it possible to access Masterpage variables from a web user control that is in a child page? I know you can access them in child pages by adding the following
<%# MasterType VirtualPath="~/Master.master" %>
It doesn't seem to work when trying to access from a Web control that is inside a child page
User Controls essentially should be unaware of any pages outside the control. The better approach would be to have the control expose properties and events that the page itself (master page or normal) will use to set and retrieve values. Take this simple example:
class PassValueEventArgs : EventArgs
{
public string Value { get; set; }
}
public event EventHandler<PassValueEventArgs> RequestingValue;
public void ControlDoingWork()
{
PassValueEventArgs e = new PassValueEventArgs();
if (RequestingValue != null)
{
RequestingValue(this, e);
}
string fromHandlingPage = "Received " + e.Value + " from a handling page.";
}
Then whenever the user control should have a value, the page containing the user control can just handle the RequestingValue event and send the value to the user control. Otherwise just expose a public property of the user control, which you can even make databound, for an even easier solution.
Adding a complete example of the event-driven approach:
WebUserControl1EventArgs.cs
public class WebUserControl1EventArgs : EventArgs
{
public double ValueToSquare { get; set; }
}
WebUserControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplicationCS1_net20.WebUserControl1" %>
Text below will display "Nothing passed from parent page." if the event is unhandled,
else will display the square of the number passed if handled.<br /><br />
<asp:Label runat="server" ID="Label1" Font-Bold="true" Font-Size="Larger" Text="Nothing passed from parent page."></asp:Label>
WebUserControl1.ascx.cs
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public event EventHandler<WebUserControl1EventArgs> RequestingNumber;
protected void Page_Load(object sender, EventArgs e)
{
ControlDoingWork();
}
private void ControlDoingWork()
{
if (RequestingNumber != null)
{
WebUserControl1EventArgs e = new WebUserControl1EventArgs();
RequestingNumber(this, e);
Label1.Text = (e.ValueToSquare * e.ValueToSquare).ToString();
}
}
}
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplicationCS1_net20.WebForm1" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<!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 id="form1" runat="server">
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server"
OnRequestingNumber="WebUserControl11_RequestingNumber" />
</div>
</form>
</body>
</html>
WebForm1.aspx.cs
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void WebUserControl11_RequestingNumber(object sender, WebUserControl1EventArgs e)
{
e.ValueToSquare = 3.3;
}
}
WebForm2.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplicationCS1_net20.WebForm2" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<!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 id="form1" runat="server">
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</div>
</form>
</body>
</html>
WebForm2.aspx.cs
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
Use the Page's Master property to access to it's masterpage. After that you can you FindControl method or use the master's public properties if it have any. For example in the master page code behind:
public Label Title { get { return lblTitle; } }

ASP.NET Content Web Form - content from placeholder disappears

I'm attempting to set a class on the body tag in my asp.net site which uses a master page and content web forms. I simply want to be able to do this by adding a bodycssclass property (see below) to the content web form page directive.
It works through the solution below but when i attempt to view Default.aspx the Content1 control loses its content. Any ideas why?
Here is how I'm doing it. I have a master page with the following content:
<%# Master Language="C#" ... %>
<html><head>...</head>
<body id=ctlBody runat=server>
<asp:ContentPlaceHolder ID="cphMain" runat="server" />
</body>
</html>
it's code behind looks like:
public partial class Site : MasterPageBase
{
public override string BodyCssClass
{
get { return ctlBody.Attributes["class"]; }
set { ctlBody.Attributes["class"] = value; }
}
}
it inherits from:
public abstract class MasterPageBase : MasterPage
{
public abstract string BodyCssClass
{
get;
set;
}
}
my default.aspx is defined as:
<%# Page Title="..." [master page definition etc..] bodycssclass="home" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphMain" runat="server">
Some content
</asp:Content>
the code behind for this file looks like:
public partial class Default : PageBase { ... }
and it inherits from :
public class PageBase : Page
{
public string BodyCssClass
{
get
{
MasterPageBase mpbCurrent = this.Master as MasterPageBase;
return mpbCurrent.BodyCssClass;
}
set
{
MasterPageBase mpbCurrent = this.Master as MasterPageBase;
mpbCurrent.BodyCssClass = value;
}
}
}
This works for me now...
public class PageBase : Page
{
public string BodyCssClass
{
get;
set;
}
protected override void OnPreInit(EventArgs e)
{
MasterPageBase mpbCurrent = this.Master as MasterPageBase;
mpbCurrent.BodyCssClass = BodyCssClass;
base.OnLoadComplete(e);
}
}
Have you tried adding the MasterType directive to your content page? Like so:
I recommend doing that anyway. Let's see if that helps you...
See http://msdn.microsoft.com/en-us/library/ms228274.aspx
and http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx

Resources