How to make user control load once? - c#

I have one user control,named as "SocialShareElements", which's purpose is to share the page content/image into FaceBook.
I utilized this user control in my Index page.
I called this user control in a "IF" condition, within Index.aspx.
The pseudo code is like:
<%
if (Request.IsSecureConnection)
{
%>
<div class="deal-detail-head tzsg-margin-bottom-med">
<MyControl:SocialShareElements ID="SocialShareElements1" runat="server"/>
</div>
<div class="clear-both"></div>
<%
}
else
{
%>
<div class="deal-test bottom-small">
<MyControl:SocialShareElements ID="SocialShareElements" runat="server"/>
</div>
<%
}
%>
When I test the FBShare function in https://developers.facebook.com/tools/debug/og/object/, it showed failed becuase I loaded "SocialShareElements" twice, and this makes meta data of "SocialShareElements" double in Index.aspx.
My question is how to adjust the logic of utilizing "SocialShareElements" in Index.aspx, to make it only be loaded once.
Thank you.

You can achieve this from code-behind.
Modify your div on your aspx page to be available from server side:
<div id="socialShare" runat="server">
</div>
In your code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.IsSecureConnection)
{
SocialShareElements shareElement = LoadControl("SocialShareElements.ascx") as SocialShareElements;
socialDiv.Controls.Add(shareElement);
}
}

Related

ASP.net User control not recognized

I am trying to add a user control dynamically to an asp.net web page.
user control code:
<%# Control ClassName="CustomParameterView" %>
<script runat="server">
public string Value { get; set; }
public string Description { get; set; }
public string Name { get; set; }
private void Input_OnTextChanged(object sender, EventArgs e)
{
Value = Input.Text;
}
</script>
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" id="DisplayName"></label>
<div class="col-sm-3">
<asp:TextBox ID="Input" runat="server" CssClass="form-control" OnTextChanged="Input_OnTextChanged" />
</div>
</div>
</div>
I have added the register line in the .aspx file:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PerCHW.Valkyrie.Server.WebApplication._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<%# Reference Control="CustomParameterView.ascx" %>
...
The problem is that this:
var control = (CustomParameterView) LoadControl("CustomParameterView.ascx");
does not compile.
I also saw people trying ti add the ASP. before the UC name but that does not work as well...
What am I doing wrong?
It looks like you are not adding the control to a PlaceHolder.
In the .aspx page add a PlaceHolder:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
And then add the Control to the PlaceHolder in code behind:
var control = (CustomParameterView)LoadControl("~/CustomParameterView.ascx");
PlaceHolder1.Controls.Add(control);
Make sure this code is called every time the page is loaded, so don't put it inside a !IsPostBack check or the Control will be gone after PostBack.

Use model on SharePoint application page .aspx

I am working on SharePoint to create a Feedback questionnaire form using an application page that is basically a aspx page.
I wish to do this by emulating MVC as far as possible. I've set up my model in the code-behind:
public List<QuestionViewModel> modelQuestions = new List<QuestionViewModel>();
Next, I need to display each question and an appropriate input depending on the question type (e.g. single line, multi line, single selection, multiple selection).
I've got it displaying the questions correctly:
<fieldset class="what-went-wrong">
<% for (int i = 0; i < modelQuestions.Count; i++) { %>
<p>
<label for="QuestionText">
<% if (modelQuestions[i].Required) { %>
<span class="req-field indicator">*</span>
<% } %>
<%= modelQuestions[i].QuestionText %>
<% if (modelQuestions[i].Required) { %>
<span class="req-field right">* Required field</span>
<% } %>
</label>
</p>
<% } %>
</fieldset>
This give's me the question text. I'm now trying to construct the appropriate input, but this <% %> tags is not working for this:
<% if(modelQuestions[i].QuestionTypeId == QuestionType.SingleLine) { %>
<input id="modelQuestions_<% i %>" name="modelQuestions[<% i %>]" type="text" placeholder="<% modelQuestions[i].Placeholder %>" />
<% } %>
I can't seem to get it to construct the html element using details from the model (in the value for id, name, placeholder etc.)
Also, I've no idea how to go about posting this back to the server when I get to that point.
Is there any merit in continuing? Are there other controls/methods more appropriate to use in this case with aspx?
You cannot generate HTML markup like this. Even data-binding expressions will not help, because they bind ASP.NET controls' attributes values, not the plain output HTML in the page.
You should generate the markup in the "code behind", like this:
Page markup:
<div id='AnswersPanel'>
<div>
Page code behind:
protected void PageLoad(...)
{
AnswersPanel.InnerHtml = "";
AnswersPanel.InnerHtml += string.Format("<input id='modelQuestions_{0}' name='modelQuestions[{0}]' type='text' placeholder='{1}' />",
i.ToString(),
modelQuestions[i].Placeholder);
}

session verification masterpage (?) asp.net c#

I have a blank page with two buttons.
the first button's click code is this:
Session["permissionUser"] = "1";
and here's the second button code:
Session["permissionUser"] = "2";
and then i have a hyperlink which redirects to the "main" website.
my objective is to adapt the menu bar which is on the masterpage based on the permission saved in the session. here's part of my code in the masterpage:
<body>
<div id="menuBar">
Home
<% if (Session["permissionUser"] == "1"){ %>
PERMISSION 1 LINK
<% } %>
<% if (Session["permissionUser"] == "2"){ %>
PERMISSION 2 LINK
<% } %>
</div>
<div id="content">
<asp:ContentPlaceHolder ID="websiteContent" runat="server"></asp:ContentPlaceHolder>
</div>
</body>
the problem is when i run the application, even if i click any of the buttons the menu doesnt adapt at all. it just shows the hyperlink "Home" and not any of the others which were supposed to be shown since the session is either 1 or 2 (depending on which button i clicked)
i cant really see what im doing wrong so if you guys have any suggestions i'd be really grateful
Your code is very PHPish. That is to say, it's ugly. And unwieldy. Let's put the logic in the code behind. We also need a form so we can have controls that run on the server.
public void Page_Load(object sender, EventArgs e)
{
//you should probably also check to make sure the session has "permissionUser" in it
if (Session["permissionUser"] == "1")
{
Permission1HL.Visible=true;
}
else if(Session["permissionUser"] == "2")
{
Permission2HL.Visible=true;
}
}
And change your ASPX page to this.
<body>
<form runat="server">
<div id="menuBar">
Home
<asp:HyperLink runat="server" id="Permission1HL" Text="Permission 1 Link" Visible="false" />
<asp:HyperLink runat="server" id="Permission2HL" Text="Permission 2 Link" Visible="false" />
</div>
<div id="content">
<asp:ContentPlaceHolder ID="websiteContent" runat="server"></asp:ContentPlaceHolder>
</div>
</form>
</body>
I suggest that you make a serverside hyperlink control instead, and set the text and navigateurl from codebehind
<asp:HyperLink id="hyperlink1"
NavigateUrl="http://mydefaulturl.com"
Text="DefaultText"
runat="server"/>
from code behind:
if (Session["permissionUser"] == 1)
{
hyperlink1.NavigateUrl = "#"
hyperlink1.Text = "Permission 1 link"
}...
This will allow you to better control and debug your values.
I would actually be more specific in the if statement
<% if (Session["permissionUser"].toString() == "1"){ %>
with null checks
<% if (Session["permissionUser"] != null && Session["permissionUser"].toString() == "1"){ %>

Clear Output Cache from User Control in Asp.Net

i have a user control with a name uc_Menu.ascx. The menues are loaded dynamically Role base. So, i inlude it in a user control and cached it like this;
Note: for testing purpose i have just provide 60 sec cache;
<%# OutputCache Duration="60" VaryByParam="none" %>
<td id="Menu">
<div id="firstpane" runat="server" class="menu_list">
<p class="menu_head">
<a href="/forms/Dashboard.aspx">
<span style="background: url('/App_Themes/Default/Images/icons/ic_grid.png') no-repeat"></span>
DashBoard
</a>
</p>
</div>
</td>
The code behind looks like this;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BulitMenus();
Response.Write("<h1>" + DateTime.Now.ToString() + "</h1>");
}
}
My master page where i have referenced the above user control;
<%# Register Src="~/UserControls/uc_Menu.ascx" TagPrefix="Ken" TagName="Menu" %>
<Ken:Menu runat="server" id="Menus" />
Now, when i tested this, it works fine (when page is loaded for the first time, cache worked)
However, I want to clear the cache when a user click on LogOff button (on a master page) because the menus are role base and an admin might give more permissions to user. In that case it is necessary to relode the menus again.
So, How do i clear the cache from a user control;
Note: I have also tried this but it deosn't work;
http://aspalliance.com/668_Remove_ASPNET_Page_Output_Cache_Entries
AND
protected void Lbtn_LogOff_Click(object sender, EventArgs e)
{
HttpResponse.RemoveOutputCacheItem("/UserControls/uc_Menu.ascx");
// this code is copied from a url above which i have included i my question
HttpContext.Current.Cache.Insert("Pages", DateTime.Now, null,
System.DateTime.MaxValue, System.TimeSpan.Zero,
System.Web.Caching.CacheItemPriority.NotRemovable, null);
FormsAuthentication.SignOut();
Response.Redirect("~/authorization/Login.aspx");
}

Manipulating a control in a child from the parent page

The answer is probably obvious but I have not seen anything I could use except the opposite - manipulating the parent from the child - so I'm posting new.
I have a shopping cart system I'm working on that my company purchased and I'm new to .NET so I may not even ask this properly.
My store has a page in the checkout portion that looks basically like this:
PaymentPage.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="PaymentPage.ascx.cs" Inherits="ConLib_PaymentPage" %>
<%# Register Assembly="CommerceBuilder.Web" Namespace="CommerceBuilder.Web.UI.WebControls" TagPrefix="cb" %>
<%# Register Src="~/Checkout/PaymentForms/CreditCardPaymentForm.ascx" TagName="CreditCardPaymentForm" TagPrefix="uc" %>
<ajax:UpdatePanel ID="PaymentAjax" runat="server">
<ContentTemplate>
On page controls, etc.
Then a checkbox saying they've read the terms and agree:
<div id="terms">
<asp:CheckBox ID="AgreeTerms" runat="server" Text="I agree to the Terms Of Service" CssClass="Terms" AutoPostBack="True" OnCheckedChanged="AgreeTerms_Clicked"/>
</div>
The task I want to accomplish is in the OnCheckedChanged event I want to enable or disable an imagebutton inside the CreditCardPaymentForm control.
That code looks like this:
<%# Control Language="C#" ClassName="CreditCardPaymentForm" EnableViewState="false" %>
<%# Register Assembly="CommerceBuilder.Web" Namespace="CommerceBuilder.Web.UI.WebControls" TagPrefix="cb" %>
<%# Register assembly="wwhoverpanel" Namespace="Westwind.Web.Controls" TagPrefix="wwh" %>
... a <script> block with some code and then HTML
<span class="TTAActionButton">
<br>
<asp:ImageButton ID="CreditCardButton" runat="server" ToolTip="Pay With Card" SkinID="TTAPlaceOrder" OnClick="CreditCardButton_Click" />
<asp:HiddenField runat="server" ID="FormIsSubmitted" value="0" />
<br /><br /><br />
</span>
I want to be able to turn the CreditCardButton on and off depending on whether the checkbox is checked. I would have a routine in the page codebehind like:
public void AgreeTerms_Clicked(object sender, EventArgs e)
{
if (AgreeTerms.Checked)
CreditCardButton.Enabled = false;
}
but every permutation of that I try has failed.
I have abbreviated the code but if I've left out too much please let me know.
Thanks for your help and if you assume I know nothing about .NET then double-thanks!
Jim
In the CreditCardPaymentForm control create a property that exposes the CreditCardButton visibility and than use that from the parent in the OnCheckedChanged function handler.
public bool ShowCreditCardButton
{
get { return CreditCardButton.Visable; }
set { CreditCardButton.Visable = value; }
}
Does CreditCardPaymentForm include a PaymentPage.ascx? That is, does the form 'use' the PaymentPage user control?
if so, your best bet it is to publish an event on PaymentPage that is raised by the checking of the checkbox:
public void AgreeTerms_Clicked(object sender, EventArgs e)
{
if (AgreeTerms.Checked)
OnTermsAgreed();
}
private void OnTermsAgreed()
{
// raise TermsAgreed event
var evt = TermsAgreed;
if (null != evt)
evt(this, EventArgs.Empty);
}
public event EventHandler TermsAgreed;
Then CreditCardPaymentForm subscribes to that event and 'does its thing' which in your case is to enable the button it knows about.

Categories