I'm teaching myself to use a site.master page with child webforms embedded using the ContentPlaceHolderID object. I'm figuring it out, but I have one question; is it possible to put a button on the site.master page that fires code on the codebehind pages of the child forms? If I can do that, it will really simplify what I'm trying to accomplish.
I tried to 'inherit' both codebehinds, but of course that didn't work. Is there a way to do this?
Yes there is a way to do this. You need to set UseSubmitBehavior button property to false and then you can access the control that causes the post back using Request.Params.Get("__EVENTTARGET"); So the code would look like this:
Button definition in Site.Master markup:
<asp:Button ID="MyButton" runat="server" Text="Button" UseSubmitBehavior="false" />
code behind within any inherited page:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// in case you have code to be executed on first load
}
else
{
string myButtonCtrl = Request.Params.Get("__EVENTTARGET");
if (myButtonCtrl != null && myButtonCtrl.EndsWith("MyButton"))
{
// MyButton has been clicked!
}
}
}
Related
I have one master page with two content page each content page has submit button:
<asp:ImageButton runat="server" type="image" id="buttonSubmit" name="buttonSubmit"
alt="ImageButton 1" src="images/button.png" OnClientClick="PreventExitPop=true"/>
I want to be able to create one onclick event on the masterpage.cs:
protected void buttonSubmit_Click(object sender, EventArgs e)
{
//
}
and attach the two buttons from the content pages to this event.
<asp:ImageButton runat="server" type="image" id="buttonSubmit" name="buttonSubmit"
alt="ImageButton 1" src="images/button.png"
onclick="buttonSubmit_Click"
OnClientClick="PreventExitPop=true"/>
The problem is that each content page knows only his code file and not the masterpage.cs.
You could write event handlers for each control and in those handlers you call a event handler method in the master page
protected void buttonSubmit_Click(object sender, EventArgs e)
{
((MasterType) this.Master).buttonSubmit_Click(sender, e);
}
i think you should not be able to do that,
and its not true that a event handler bind to two separate event at all...
i think, if you can, you should create your button on master page...
if you can not, you should have two event handler for these buttons, but u can create a method and in this method do everything you want, and call this method from two defined handlers...
This has to be the simplest thing in the world but it just isn't working.
I have an outer div to which I want to apply a class to make its display style = none so that it hides all the content within it. It's actually an asp:panel element so I'm assuming I can just set control.CssClass = "my-hidden-class" in the code behind.
I'm actually setting this on a button click handler(depending on certain conditions) But the class is never applied. When I inspect the div element in Firebug it doesn't even have a class attribute. It appears exactly as it is in the .aspx markup (the actual css class is fine & gets applied when I add it declaratively).
Also, I can see the class applied if I set CssClass in the prerender method on the initial get request. So I thought maybe I'll put all the logic in prerender and update the Css Class accordingly. This also doesn't work - the class gets applied on the initial get ok but I can't change it subsequently.
So, to sum up it seems I can't apply class from code behind at all in the event handler and I can only apply it in prerender for the intial get request & this value is persisted on all postbacks.
What am I doing wrong?
Edit: Here's the code -
aspx:
<asp:panel runat="server" ID="TariffContainer"><!--this is the div I want to toggle-->
<cms:ContentBlock ID="currentTariffsInfo" SkinID="Public/OurPrices/CurrentTariffsInfo" runat="server" />
<ucTcrPanel:tcrpanel ID="tcrpanel" PagingEnabled="true" runat="server" />
<div class="quick-price">
<asp:LinkButton runat="server" CausesValidation="false" ID="QuickEnergyPrice" OnClientClick="Javascript:return false;" CssClass="button subcontent"><span>Get a quick energy price</span></asp:LinkButton>
</div>
<div class="not-for-sale">
<cms:ContentBlock ID="preservedTariffsLinkInfo" SkinID="Public/OurPrices/PreservedTariffsLinkInfo" runat="server" />
<p>
<asp:LinkButton runat="server" CausesValidation="false" ID="ViewNotAvailableTariffs" OnClick="RedirectToUnavailableTariffs" cssclass="arrow">View tariffs not available for sale</asp:LinkButton>
</p>
</div>
</asp:panel>
Code Behind:
protected void PostCodeChange_BtnClick(object sender, EventArgs e)
{
if (IsValid)
{
tcrpanel.ApplyPostcodeUpdate(postcode.EnteredPostCode);
tcrpanel.TcrUpdatePanel.Update();
}
else
{
TariffContainer.CssClass = "formContentHidden";
}
}
Update - The button click event is coming from a user control & this is wired up to trigger an update on an update panel - i.e. a partial postback is happening. I'm doing this hiding & showing of the div in the containing aspx page & even though all the server side page events are executing I'm guessing that the content of the page isn't getting re-rendered so I'm not seeing my changes.
The Solution - I ended up squirting a bit of javascript down from the server:
protected void PostCodeChange_BtnClick(object sender, EventArgs e)
{
tcrpanel.ApplyPostcodeUpdate(postcode.EnteredPostCode);
tcrpanel.TcrUpdatePanel.Update();
}
Then in the tcrpanel user control code behind:
public void ApplyPostcodeUpdate(string postcode)
{
if (IsValid)
{
BuildStartUpScript("showTariffContainer();");
}
else
{
BuildStartUpScript("hideTariffContainer();");
}
}
private void BuildStartUpScript(string functionCall)
{
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
script.AppendLine(functionCall);
script.AppendLine("</script>");
ScriptManager.RegisterStartupScript(pnlUpdateTcr, pnlUpdateTcr.GetType(), "HideTariffContainerScript", script.ToString(), false);
}
Then in the included JS file:
function hideTariffContainer() {
$("div.formContentVisible").toggleClass().toggleClass("formContentHidden");
}
function showTariffContainer() {
$("div.formContentHidden").toggleClass().toggleClass("formContentVisible");
}
As suspected, the problem was that a partial postback was occurring in which only the contents of the update panel were being re-rendered.
That said, all the server side page lifecycle events were still being invoked. This is what confused me as I could debug and see the CssClass being applied but not being rendered in the html. Just the way Asp.Net update panels work I guess.
My code:
protected void btnOk_Click(object sender, EventArgs e)
{
if (txtReportFavorite.Text != string.Empty)
{
//..
}
else
{
Response.Write("<script>alert('Enter Favorite name.')</script>");
// I need to prevent page refresh here.
}
}
How can I stop refreshing the page in the else condition. Thanks.
You can't.
The new page has already been requested when that code runs. If you don't do a postback, that code will never run.
If you want to do the validation without doing the postback, you should do it using client code instead.
The fact that you got to the server side means that your page has done a full cycle to the server and refreshed itself.
Unless you are calling this code with an Ajax call.
You can also achieve this by placing an AjaxUpdatePanel around your button that will simulate an Ajax call when your clients will submit your form.
in your code behind on page load put this
btnOk.Attributes.Add("onclick","return validate();");
in your aspx file have this script
function validate()
{
if(document.getElementById("txtReportFavorite").value == "";
{
alert("Enter Favorite name");
return false;
}
}
Your page is already go to the server side and it is in already postback is progressing.
you have to use client side code for preventing postback.
why not to use RequiredFieldValidator if only empty textbox need to validate?
you can do it on client side.
<asp:TextBox runat="server" id="txtReportFavorite" />
<asp:RequiredFieldValidator runat="server" id="txtReportFavorite" controltovalidate="txtName" errormessage="Enter Favorite name!" />
<br />
<asp:Button runat="server" id="btnSubmit" text="Ok" onclick="btn_Click" />
protected void btnSubmitForm_Click(object sender, EventArgs e)
{
if(Page.IsValid) //for secure validation
{
//do something
}
}
Try using RegisterScriptBlock.
ClientScript.RegisterStartupScript(this.GetType),"","$(document).ready(function(){alert('Enter Favorite name.')});",true);
If you want to perform from server-side do it like above.. Otherwise many answers already posted.
The kind of functionality you are showing can be easily achieved by using a Validator so the page won't post back.
As once it reaches the server, its really not possible to stop the refresh. Well, at least as far as I know.
-Milind
I have a user control which has html elements like <input type="button".... and i want to set its display property on preRender state.
Would you please explain, what kind things i have to handle this user control? So, in this function
protected override void OnPreRender(EventArgs e) { }
I have only EventArgs e and it doesn't have proper method or properties to bring me the html of user control.
Thank you from now...
The easiest way to control visibility of elements from the server side is to promote them to server controls. For example:
<input id="mybutton" runat="server" type="button" ...
Doing so would allow you to execute a statement like the following in your OnPreRender() event:
mybutton.Visible = false; // removes the element
Or...
mybutton.Style[HtmlTextWriterStyle.Display] = "none"; // styles the element
We are running following javascript function:
function btn_AddToList_Click() {
var filePath = document.getElementById("FileUpload").value;
if(filePath.length > 0)
{
var opt = new Option(filePath,filePath);
var listBox = document.getElementById("ListBox");
listBox.options[listBox.options.length] = opt;
}
}
Function binding:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btn_AddToList.Attributes.Add("onclick", "btn_AddToList_Click(); return false;");
}
}
HTML:
asp:FileUpload ID="FileUpload" runat="server" Width="394px"
asp:ListBox ID="ListBox" runat="server" Width="394px"
asp:Button ID="btn_AddToList" runat="server" Enabled="true" Text="Add"
Issue is that value of "FileUpload" is not get cleared after we click "Add" button. Any help?
You can not set/clear the value of FileUpload control programmatically. That is a restriction for a security reason. Consider this if this restriction was not there, you could set the value of FileUpload control to some arbitrary file and upload it to your server. You won't be able to achieve this in current shape.
As a work around you can try to bring another textbox exactly on top of textbox part of FileUpload control. This way you will be give the same feeling what you are trying to achieve. But that is also not ideal and may not work properly.