Script from ascx file use in ascx.cs - c#

I have one script from ascx file to hide the popup page. This script currently use when user click cancel button.
Script in ascx file:
<script>
function HidePopup() {
$find("mpeDiscountedProducts").hide();
return false;
}
I want to use this script in ascx.cs (behind code) to hide the popup when user click on select button.
Below code that i want to place the script:
protected void btnSelect_Click(object sender, EventArgs e)
{
RemoveDiscountedItemsFromCart();
AddToCart(1);
this.Page.GetType().InvokeMember("CallFromDiscountProduct", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, null);
}
Thanks.

Call
Page.ClientScript.RegisterStartupScript(
this.GetType(), "Hide_mpeDiscountedProducts", "HidePopup()", true);
Documentation
"Hide_mpeDiscountedProducts" is an arbitrary key that identifies the script so that you can avoid registering it twice if another control on the page might potentially register the same script.
Your button is going to trigger a postback so the page is going to refresh. When the page refreshes it will contain a <script> tag containing a call to HidePopup().

Related

ASP.Net C# - Redirect to a page

I've got a 'menu' within a Master page which includes a number of image buttons with click events.
Within each click event, I want to redirect the user to a specific (Child) page. However, if the user is already on the correct (Child) page, I don't want to refresh the page and lose the entered data.
In the example below, I want to redirect the user to browse.aspx however, if the user is already on browse.aspx, I don't want to refresh it.
Is there a better way to do this than the following?
protected void ibtnBrowse_Click(object sender, ImageClickEventArgs e)
{
if (!Request.Url.Segments[1].ToString().Equals("browse.aspx"))
{
Response.Redirect("~/browse.aspx");
}
}
How about disabling the Image button on the page?
e.g.
When you are on browse.aspx, in code behind browse.aspx.cs you can disable the button.
ImageButton iBtn = (ImageButton)Page.Master.FindControl("ibtnBrowse");
iBtn.Enabled = false;
By having server side click events the page will always "refresh" when clicking on these buttons. However, if you are simply looking to avoid doing an unnecessary redirect in your code you can use:
HttpContext.Current.Request.Url.AbsoluteUri
or
HttpContext.Current.Request.Url.AbsolutePath
If you decide to use javascript to switch between pages you can use location:
location.replace("http://www.w3schools.com");
location.assign("http://www.w3schools.com");

Does C# has any methods to execute Javascript function when button is pressed?

My situation is following:
I have OnTextChanged event handler on my aspx page, what calls TextChanged() method from code-behind. Now, I need to run a javascript script at the end of that TextChanged() method. How can I do this? Does ScriptManager have any methods what will execute the scripts only then when I change text in my textbox?
I might be a duplicate question, but I couldnt find information whether the scriptmanager has any methods that will run script immediately after registering it.
The actual problem is that, I need to put a script at the end of TextChanged() method and the script will just have to set focus from one html element to another.
You can simply send the required JavaScript in the code behind itself:
public void TextChanged(object sender, EventArgs e)
{
//...
this.ClientScript.RegisterStartupScript(this.Page.GetType(), "text_changed", "alert('Text was changed');", true);
}
This will show the alert only after TextChanged() is executed in the code behind.
If you're not inside a Page instance (e.g. static library) have such code, assuming you're in the context of a Page and not in some HTTP Module or something like that.
ScriptManager.RegisterStartupScript(HttpContext.Current.Handler as Page, typeof(Page), "text_changed", "alert('Text was changed');", true);
write below code in text changed function where you want to execute script. And put your java script function name in place where i bold text
**>ClientScript.RegisterStartupScript(this.GetType(), "Javascript","JavaScriptFunctionName()", true);**

How to close a modal window after a save in Asp.NET WebForms

I have some javascript code on my main page that opens a popup when a link is clicked on:
<script language="javascript">
function OpenResidentialAddressWin(subscriberContactRelationGid, routeId, btn) {
window.showModalDialog("SubscriberResidentialAddress.aspx" + BuildQueryStringValuesForSubscriber(subscriberContactRelationGid, routeId, returntxtReceiptDate().value), this, strWindowFeatures + ";scroll:no;dialogWidth:442px;dialogHeight:350px");
location.href = location.href;
}
</script>
So the above code opens up the page SubscriberResidentialAddress.aspx in a modal window (as well as passing a number of variables into this page)
Now this page is arranged in such a way that it either displays or edits information. (These are in separate divs that are displayed or hidden dependign on what buttons have just been pressed in the window).
Currently after a user makes a save to the information on the page it switches to display mode. Instead I want to close the modal window completely and reload the main page.
A colleague suggsested that I use a literal control on the aspx page of the modal window and write javascript to it after a successful save has been carried out. So I placed the following in the head section of the SubscriberResidentialAddress.aspx page:
<asp:Literal runat="server" ID="litCloseWind"></asp:Literal>
And then in the code behind in the function that is called when a save is carried out
protected void btnAddSave_Click(object sender, EventArgs e)
{
////// code related to saving
if (status.IsSuccessful)
{
litCloseWind.Text = "<script>this.close()</script>";
Response.Redirect(Request.Url.AbsoluteUri, false);
}
}
I have tried the above and also litCloseWind.Text = "window.close()"; but neither were successful in closing the modal window after a save is carried out.
Is this plan logically sound and have I just made an error somewhere or was this a bad way of doing it to begin with?
Why don't you register a script here, like this:
ClientScript.RegisterStartupScript(typeof(Page), "CLOSEWINDOW", "window.close();");
No need of putting any Literal Control here.
So your code will look something like this:
protected void btnAddSave_Click(object sender, EventArgs e)
{
if (status.IsSuccessful)
{
ClientScript.RegisterStartupScript(typeof(Page), "CLOSEWINDOW", "window.close();");
}
}

jquery used only on codebehind boolean = true

I have a modal popup div that displays when a textbox is clicked. However, I only want this functionality if the user has permissions to this feature, otherwise I want to completely ignore all code associated with the textbox being clicked (ie. the user will just type values into the textbox). How can I set the JQuery code for textbox click, to only happen based on a boolean variable retrieved in the codebehind from the database?
You can warp the script with a literal control, and open/close it if have permissions as:
<asp:Literal runat="server" id="MoreScript" EnableViewState="false">
<script>
functions MoreToDo(){
}
</script>
</asp:Literal>
and on code behind you just set the MoreScript.Visible according to your permissions. I select the Literal because you can add it on the header and is not leave any marks, and also you can direct see the javascript code on page.
I would do something like this probably
<script>
if ("<%= CodeBehindProperty %>" == "true")
{
//Attach click events
}
</script>
You could try to register the jQuery function from codebehind by useing RegisterStartupScript method.
public void Page_Load(Object sender, EventArgs e)
{
String scriptString = #"<script type='text/javascript'>
$(document).ready(function($){
$('#Element').click(function(){
//open popup
});
}
</script>";
if(hasPermission())
this.RegisterStartupScript("PopUpScript", scriptString);
}

How to load javascript function from an dynamicall added control?

The Master page got a ScriptManager.
Then i got a Control with a ScriptManagerProxy and an UpdatePanel.
Inside the UpdatePanel there I dynamically add a Control (also containing a ScriptManagerProxy) and from that control I need to run some JavaScript code.
DynamicControl.ascx:
<script type="text/javascript">
function doSomething() {
alert(1);
}
</script>
DynamicControl.ascx.cs:
public void Page_Load(object sender, EventArgs e)
{
...
ScriptManager.RegisterStartupScript(
this.Page, this.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
My problem is that the function "doSomething()" is never called and i dont know why. :S
Edit: It is called but not directly when i add the control.
If I do code like this, there will be an alertwindow:
"<script type='text/javascript'>alert(1);</script>"
Ok I think i need to add some more information:
The control is dynamical added inside a jQuery Dialog. And I found out that the javacode is first executed after i close and then open the dialog. Some kind of event is triggered so that the code is executed there i think. Is it possible to force this event? so the scripts are executet directly when the control is added ?
placeHolder.Controls.Add(dynamicReportControl);
This c# code doesn't execute the javascript tag immediately ?
Please try something like this
ScriptManager.RegisterStartupScript(
this.UpdatePanel1, this.UpdatePanel1.GetType(), "scriptID",
"<script type='text/javascript'>doSomething();</script>", false);
Where UpdatePanel1 is your UpdatePanel
Try setting the addScriptTags argument to true, and remove the script declaration from your code.
Is that code only supposed to run on every request? If so, why not just add this code to the ASCX:
window.onload = doSomething();

Categories