ClientScript.RegisterStartupScript NOT working on server - asp.net

I'm having troubles with the following piece of code. It works really good in my local machine, but when I deploy it in the dev server it doesn't work at all. I've searched in a lot of places for a solution but with not successfully.
I have a gridview in which one column is a buttonfield. This button field opens a popup displaying the detail of the selected sales order.
In order to show the popup I use the following sentence:
private void OpenPopup(string name_)
{
Page.ClientScript.RegisterStartupScript(typeof(home), "Popup", string.Concat("<script type='text/javascript'>OpenPopup('", name_, "');</script>"));
}
The OpenPopup() is a javascript function which simply displays the popup (I've tested it and it works fine, so I wont show unnecessary code):
When RegisterStartupScript is executed in my local enviroment it works fine and the result in the page source is the following:
<script type='text/javascript'>OpenPopup('items');</script>
Now, when I publish the site and deploy it in the server it doesn't work at all. I've already tried to make it work using Scriptmanager, but with the same result; it works locally but not in the server.
The added script isn't being written at all.
I really apretiate any kind of help. I've already searched a lot with lots of approaches but no solution for me...
Thanks a lot.
/Edit: I do not use updatepanel in the page.

Have you tried using .RegisterClientScriptBlock? This is what I always use in order to call the JS in the codebehind.
Could you try something like the code below?
protected void btnSubmit_Click(object sender, EventArgs e)
{
Boolean dne = false;
StringBuilder errorMessage = new StringBuilder();
String scriptName = "";
if (AdminAccess.DoesUserExist(txtUsername.Text))
{
errorMessage.Append("alert('The selected username " + txtUsername.Text + " is already in use. Please choose another. ');");
scriptName = "duplicateUsername";
if (!ClientScript.IsClientScriptBlockRegistered(scriptName))
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), scriptName, errorMessage.ToString(), true);
}
dne = true;
}
}

Related

How to create an IIS website that runs a PowerShell function and shows its output?

I've created a PowerShell function (called Get-FileInUse) that will parse our data server for a list of known files.
The function returns ($global:result as array) which files are in use and by whom.
I'd like to host an internal website that shows (when accessing it or when pressing a button on the site) the output of this function. Say an internal website inusefiles.corp.com. Don't bother about bindings and DNS records, I'll manage that.
I've followed a tutorial online (this one), but it's hard to understand what's going on.
These are my two questions:
How do I add my script in the aspx.cs file? I would like to have the script run when loading the page. Placing it under protected void Page_Load(object sender, EventArgs e) seems logical to me.
My function returns a variable $result. How do I show it in eg. a text box?
Note: I don't have any experience with ASP.NET/Web Forms. PowerShell is no problem for me.
Okay, found it:
Under protected void Page_Load(object sender, EventArgs e) came:
string scriptOutput = "";
using (var ps = System.Management.Automation.PowerShell.Create(System.Management.Automation.Runspaces.InitialSessionState.CreateDefault()))
{
ps.AddStatement().AddScript("Get-FileInUse").AddCommand("Out-String");
foreach (var res in ps.Invoke())
{
scriptOutput = string.Join(Environment.NewLine, scriptOutput, res);
}
}
Result.Text = scriptOutput;
While my Default.aspx contains a ASP Textbox with ID="Result":
<asp:TextBox ID="Result" TextMode="MultiLine" Width="50%" Height="300" runat="server">
</asp:TextBox>

How do I Redirect a new Tab with Query String in asp.net

How to open new tab window with passing ID using Query String.
I tried all the possible ways,i.e Onclientclick and others. but not.help me.
Thank you in advance
if (e.CommandName == "Items")
{
int ID = Convert.ToInt32(e.CommandArgument.ToString());
Response.Redirect("Add_Items.aspx?TestID=" + ID);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int id = Convert.ToInt32(Request.QueryString["TestID"]);
lblTestID.Text = id.ToString();
}
The server-side code can't instruct the browser to open a new tab, that's not how redirects work. All a redirect does is tell the browser to navigate to an address.
To open a new tab, you'd need to use client-side code. Generally this could be as simple as:
window.open(address, '_blank');
However, keep in mind that browsers make no standard guarantee to open things in tabs vs. new windows. That's entirely up to the browser's settings and capabilities. (I think that in some browsers it might make a difference whether this code is executed directly or in a click event.)

Response.Redirect(Request.Url.AbsoluteUri) doesn't update page data

I have Page_load method like this:
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
// Load Content
LoadContent();
return;
}
// some code here
}
And I use Response.Redirect(Request.Url.AbsoluteUri) at the end of methods to prevent re-post actions cased by page refrashing. When I run my app from source code that works well (debug or run mode), but when I publish the app (even on the same machine) page data (which loads on LoadContent) is not updated on updated page (but re-post actions is prevented).
Please, could anyone tell me why it happens?
ADDED:
There is LoadContent() method:
// firstly I get an supervisedGroups list TIBCO iProcess Engine via .NET vendor library, and then:
if (supervisedGroups != null)
{
rptSupervisedGroups.DataSource = supervisedGroups; // rpt.. is Repeater
rptSupervisedGroups.DataBind();
}
ADDED:
Method where Response.Redirect are used:
private void removeFromGroup(string strGroupName)
{
using(SqlConnection con = DBHelper.GetNewConnection())
{
con.Open();
// here comes query to DB
}
// Reload Page
Response.Redirect(Request.Url.AbsoluteUri);
}
You have two ways to solve this cache issue.
One is to give instructions to the browser to not cache this page, for example on page load you run:
Response.Cache.SetExpires(DateTime.UtcNow.AddYears(-4));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetNoStore();
But a better solution is to add a random number at the end of the url when you make the redirect, or even better add the new id from the data that you have insert, eg:
Response.Redirect("samepage.aspx?newid=" + NewId);
that way the page will forced to be readed again, and you still have the cache functionality.
Most likely your page is cached. Try to hit shift-f5 to check the content. You can make all redirect urls unique to prevent the browser showing a cached page. Or disable caching for the specific page.

How to display save confirmation message on my Web form when user saves new form by clicking Save button

I am very new to ASP.NET. I am working on some other developer's Web form. I have been asked to fix a bug which says:
No success message is displayed when user clicks Save button after
adding information to the form (first time or while updating)
There is a Label at the top of the page with ID lblMsgs
<asp:Label ID="lblMsgs" runat="server">
I have added this to the Code behind in the appropriate place:
lblMsgs.Text = "Message Text";
Now, my question is how do I modify the HTML or code behind to make sure that when Save button is clicked, the code checks that the data is saved to the database and displays save successful message on the Web form.
Can you please help by giving example of the code using my label ID above?
Thank you in advance.
That's a pretty vague question, but if your looking for data validation you should look at the built in ASP.NET Validators. This can do client/server side data validation. As for returning a message to the user based on a successful update to the DB, that is going to be solution specific depending on what type of data layer your using.
On your Save button handler, you can add validation logic if whether the data is valid or not.
protected void ValidateSave(object o, EventArgs e){
if (Page.IsValid) {
// Save to DB and notify of update status
var success = SomeDBMethod.Update...
if (success){
DoAlert("Saved Successfully!");
}
}
else { lblMsgs.Text = "Failed"; }
}
// Call client-side alert
private void DoAlert(string message) {
ClientScriptManager cs = Page.ClientScript;
var x = "alertScript";
if (!cs.IsStartupScriptRegistered(cstype, x))
{
String script = string.Format"alert('{0}', message);";
cs.RegisterStartupScript(cstype, x, script, true);
}
}

jQuery UI autocomplete is not displaying results fetched via AJAX

I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.

Resources