Adding JavaScript to page using ClientScriptManager - c#

I am trying to add JavaScript to a page using ClientScriptManager but the script does not get added to the page. 'trendsTable' contains an asp:Gridview and its display is set to none, but on click of 'RequestReport' I want data bound to the gridview, which dataTabletester does, and then for the display of 'trendsTable' to be set to table.
protected void RequestReport_Click(object sender, EventArgs e)
{
//method to bind data to table
dataTabletester();
//insert script to make table visible
String csname1 = "PopupScript";
Type cstype = this.GetType();
//Get a Client ScriptManager reference from Page Class
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
string script = "function() {document.getElementById('trendsTable').style.display = \"table\";}";
StringBuilder cstext1 = new StringBuilder();
cstext1.Append("<script type=text/javascript>");
cstext1.Append(script);
cstext1.Append("</script>");
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
}
}
Thanks to anyone who can provide any help.

You are defining a function but not calling it. Change:
string script = "function() {document.getElementById('trendsTable').style.display = \"table\";}";
to
string script = "document.getElementById('trendsTable').style.display = \"table\";";

Related

Image removing/covering all the controls on the page

So I've got this asp fileupload control which I'm using to select an image. The image is then saved in a temporary folder called "TempImages", then I'm pulling it from there and displaying it on the page, using the code shown below.
protected void Close_Click(object sender, EventArgs e)
{
Div1.Visible = false;
}
#endregion Submit button
protected void LogoToUpload_Click(object sender, EventArgs e)
{
if (upldLogo.HasFile)
{
upldLogo.SaveAs("C:\\TempImages\\" + upldLogo.FileName);
Response.ContentType = "image/jpeg";
string physicalFileName = #"C:\TempImages\" + upldLogo.FileName;
Response.WriteFile(physicalFileName);
}
My problem is that When the image is displayed, it gets rid of all the other controls, i.e. the dropdowns, the textboxs and the labels and all that jazz.
Anyone got any suggestions on how I can make the image just show either in a pop up or just display on the same page but with all the controls still there.
Cheers folks
Ok, so I managed to sort this out by using a little Javascript I put this into the head tag on the controls page.
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#<%=imgLogo.ClientID %>');
var file = document.querySelector('#<%=upldLogo.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
aaaand this into the content.
This served to create a little preview of the picture next to the file upload control once you selected a file.
Cheers!
<input ID="upldLogo" type ="file" onchange="previewFile()" runat="server" />

How do I call the object in my script in C#?

Basically, what I'm trying to do is get this script set up programmatically through C#. That part is working fine.
public static void ToolDatePicker_BS(ref StringBuilder Script, string Name)
{
Script.Append(#"<input type='text' name='");
Script.Append(Name);
Script.Append("'id='");
Script.Append(Name);
Script.Append(#"'value'/>");
Script.Append(#"<script>");
Script.Append(#" $(function() {");
Script.Append(#"$( '#");
Script.Append(Name);
Script.Append(#"' ).datepicker({");
Script.Append(#"showOn: 'button',");
Script.Append(#"buttonImage: './calendarFull.png' ,");
Script.Append(#"buttonImageOnly: true");
Script.Append(#"});");
Script.Append(#"});");
Script.Append(#"</script>");
}
Then after dynamically adding the script with the textbox object into the html, I need to call the textbox object to get and set text into it.
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
MyDatePicker.ToolDatePicker_BS(ref sb, "StartDateTextBox");
StartDateTextBoxPH.Text = sb.ToString();
StartDateTextBoxText = StartDateTextBox.Text();//This is the area with the problem.
}
Obviously since I defined the StartDateTextBox within quotes the compiler isn't gonna know it's a object now so I'm getting this error.
The name 'StartDateTextBox' does not exist in the current context
I think StartDateTextBox.Text would be a property.
How about removing those brackets:
StartDateTextBoxText = StartDateTextBox.Text;

RadWindow not opening

RadWindow not open when i click over the button
My javascript code:
<script type="text/javascript">
function OpenURL(URL) {
var oWnd1 = radopen(URL, "Detalhamento do Contrato");
oWnd1.set_height("600px");
oWnd1.set_width("600px");
oWnd1.center();
oWnd1.set_modal(true);
}
</script>
My C# code:
protected void RadGrid_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName.Equals("Detalhes"))
{
String Parametros = "ContratoNumero=" + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CONT_NUMERO"];
Parametros += "&AditivoNumero=" + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CONT_NUMADITIVO"];
Parametros += "&ContratoTipo=" + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["CONT_TIPO"];
Parametros += "&Exercicio=" + this.txtExercicio.Text;
string URL = "ContratoDetalhamento.aspx?" + Parametros;
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "relatorio", String.Format("OpenURL('{0}','{1}');", URL, DateTime.Now.Ticks), true);
}
}
Can someone help me ?
Thanks for now
You are missing:
oWnd1.SetActive();
1) look here on executing the script properly: http://www.telerik.com/help/aspnet-ajax/radwindow-troubleshooting-javascript-from-server-side.html.
2) look here on the proper radopen() syntax: http://www.telerik.com/help/aspnet-ajax/window-programming-opening.html.
Here is how I would do it:
function OpenURL(URL) {
var oWnd1 = radopen(URL, "RadWindowName");//note, no spaces
oWnd1.setSize(600, 600);//width, height
oWnd1.set_modal(true);//making it modal will center it by default
}
Now, make sure you execute the code late enough:
string script = "function(f){openURL('url'); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "someKey", script, true);
Hi I want to share with you my solution to create RadWindow dialog in Javascript code only.
We need to implement 2 methods: one for initializing RadWindow dialog, and the last one for recieving the arguments returned after closing the RadWindow. You can do what you want in this second step (e.x postback,...)
Here is my code:
Initializing RadWindow dialog:
function openMyDialog(url, args) {
var manageWindow = GetRadWindowManager();
if (manageWindow) {
var radWindow = manageWindow.open(url, "<your_dialog_name>");
if (radWindow) {
radWindow.set_initialBehaviors(Telerik.Web.UI.WindowBehaviors.None);
radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize);
radWindow.setActive(true);
radWindow.SetModal(true);
radWindow.center();
radWindow.set_visibleStatusbar(false);
radWindow.set_keepInScreenBounds(true);
radWindow.set_minWidth(640);
radWindow.set_minHeight(480);
radWindow.setSize(640, 480);
radWindow.set_destroyOnClose(true);
radWindow.add_close(closeMyDialog);//after closing the RadWindow, closeMyDialog will be called
radWindow.argument = args;//you can pass the value from parent page to RadWindow dialog as this line
}
}
}
Closing the RadWindow dialog:
function closeMoveProjectDialog(sender, args) {
var objArgs = args.get_argument();
//objArgs variable stored the values returned from the RadWindow
//you can use it for your purpose
}
How to call this? You can put the open method into your expected method. In my side, I have a method as shown below and I will call the RadWindow as this way:
function ShowForeignKeyFrontEditSingle(param1, param2){
var url = "ForeignKeyFrontEditSingle.aspx";
var objArgs = new Array();
objArgs[0] = param1;
objArgs[1] = param2;
openMyDialog(url, objArgs);
return;
}
Of course, you have to declare a RadWindowManager control
function GetRadWindowManager() {
return $find("<%=your_radwindow_manager_control.ClientID%>");
}

How to get RadToolBarDropDown selected item value in c#

How to get the RadToolbarDropDown selected item value in code behind file. In my case I have a RadToolBar in which I dynamically create RadToolBarDropDown. I set these DropDown Value and Text dynamically as I my code shows.
RadToolBarDropDown dd = new RadToolBarDropDown();
if (ds.HasRows())
{
DataTable dt = ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
RadToolBarButton rtb = new RadToolBarButton();
rtb.Text = row["Description"].ToString();
rtb.Value = row["ProblemStatusID"].ToString();
rtb.CommandName = "StatusChange";
rtb.CommandArgument = row["ProblemStatusID"].ToString();
dd.Buttons.Add(rtb);
}
}
RadToolBarItem item = dd;
mlmToolBar.Items.Add(item);
Now I want to get selected item value in cs when command name "StatusChange" fire. I want to get the clicked value of the dropdown. How I can get the clicked dropdown value?
There are 2 ways you can handle the button click event of the dropdown items. You can handle it on server side or you can handle it on client side. Lets look at it one by one:
Server Side:
Assume I have a rad tool bar control on my page. Here is the code for the same:
<telerik:RadToolBar runat="server" ID="rtlMyToolBar"
OnButtonClick="rtlMyToolBar_ButtonClick" ></telerik:RadToolBar>
Note that I have handled the OnButtonClick event. We will look at it next.
From code behind I am adding a dropdown control and adding buttons to the drop down. Here is the code for the same:
RadToolBarDropDown dd = new RadToolBarDropDown("Drop Down - Handled Server Side");
RadToolBarButton rtb = new RadToolBarButton();
rtb.Text = "Bold";
rtb.Value = "Bold";
rtb.CommandName = "Bold";
rtb.CommandArgument = "Bold";
dd.Buttons.Add(rtb);
rtb = new RadToolBarButton();
rtb.Text = "Italic";
rtb.Value = "Italic";
rtb.CommandName = "Italic";
rtb.CommandArgument = "Italic";
dd.Buttons.Add(rtb);
rtb = new RadToolBarButton();
rtb.Text = "Underline";
rtb.Value = "Underline";
rtb.CommandName = "Underline";
rtb.CommandArgument = "Underline";
dd.Buttons.Add(rtb);
rtlMyToolBar.Items.Add(dd as RadToolBarItem);
Now lets take a look at the event handler:
protected void rtlMyToolBar_ButtonClick(object sender, RadToolBarEventArgs e)
{
var toolBarButton = e.Item as RadToolBarButton;
string commandName = toolBarButton.CommandName;
if (commandName == "YourCommandName")
{
//Your logic
}
}
Client Side:
Now lets take a look at how to listen to drop down button click on the client side. Here is the code snippet for the rad tool bar:
<telerik:RadToolBar runat="server" ID="rtlMyToolBar2"
OnClientButtonClicked="OnClientButtonClicked"></telerik:RadToolBar>
Note that now I am listening to OnClientButtonClicked event. The event handler is a javascript function reference.
Here is the javascript code:
<script>
function OnClientButtonClicked(sender, args) {
$("#status").append("OnClientButtonClicked: " + args.get_item().get_text() +
" - Command Name: " +
args.get_item().get_commandName() + "<br/>");
}
</script>
All telerik controls have a rich consistent client side and server side API.
Here is the GIST link for the above code: https://gist.github.com/lohithgn/5329716
Here is a example which show cases the client side api in our live demo site: http://demos.telerik.com/aspnet-ajax/toolbar/examples/clientside/clientevents/defaultcs.aspx
Here is the client side API basics help documentation:
http://www.telerik.com/help/aspnet-ajax/toolbar-clientsidetoolbaritem.html
Thanks

Why cant I use `Invokemember("click")` to click my button programatically?

I am trying to fetch data from a website in my application through a WebBrowserControl. I can successfully log in, but when I call btnsearch.Invokemember("click") programmatically I receive a JavaScript error. If I click the button interactively on the WebBrowserControl I receive no error and everything works fine.
In the aspx page I have one JavaScript function for calling an Ajax Panel:
<script type="text/javascript">
/*<![CDATA[*/
window["ctl00_WorkSpace_ctlCustAVIHistory_ajxResultPanel"] = new RadAjaxPanelNamespace.RadAjaxPanel({ClientID:"ctl00_WorkSpace_ctlCustAVIHistory_ajxResultPanel",EnableOutsideScripts:false,EnablePageHeadUpdate:true,Url:"/app/ModuleCustomer/ViewAVITransactions.aspx",LoadingPanelID:"ctl00_WorkSpace_ctlCustAVIHistory_LoadingPanel1",ActiveElementID:"",ClientEvents:{OnRequestStart:"",OnRequestSent:"",OnResponseReceived:"",OnResponseEnd:""},FormID:"aspnetForm",UniqueID:"ctl00$WorkSpace$ctlCustAVIHistory$ajxResultPanel"});/*]]>*/
</script>
It produces a UniqueID. If we click on btnsearch through code this unique id is null.
function onClickButton(rName)
{
if(validateData())
{
document.getElementById("ctl00_WorkSpace_ctlCustAVIHistory_hdnReset").value = "0";
ctl00_WorkSpace_ctlCustAVIHistory_ajxResultPanel.AjaxRequest("NewSearch"); ///these caling down function
}
}
RadAjaxPanelNamespace.RadAjaxPanel.prototype.AjaxRequest = function (eventArgument) {
this.AjaxRequestWithTarget(this.UniqueID, eventArgument);//this.UniqueID giving null from program click mouse click it is giving correct id
};
Any idea why this happens?
private const string STR_Field_userid = "field_userid";
private const string STR_Field_password = "field_password";
private const string STR_Submit = "submit";
document.GetElementById(STR_Field_userid).InnerText = UserId;
document.GetElementById(STR_Field_password).InnerText = Password;
document.Forms[0].InvokeMember(STR_Submit);

Categories