How to pass value of C# variable to javascript? - c#

In button click event I am writing this code.(code behind).I know button click event
protected void button_click()
{
string s1 = "Computer";
StringBuilder sb = new StringBuilder();
sb.Append(#"<script language='javascript'>");
sb.Append("document.write('<table><tbody>')";);
sb.Append("document.write('<tr><td>Information</td></tr>')";);
if(s1 == "Computer" )
{
sb.Append("<tr><td>s1</td></tr>");
}
sb.Append("document.write('</tbody></table>')";);
sb.Append(#"</script>");
}
It is working but I want value of s1 not s1.I know javascript is a client side programing.I wrote this function in button click event.How can pass value of s1 that is computer to table's cell

simply
sb.Append("document.write('<tr><td>" + s1 + "</td></tr>');");

Have you tried
if(s1 == "Computer" )
{
sb.Append("<tr><td>"+s1+"</td></tr>");
}

You could change this line to:
sb.Append("<tr><td>" + s1 + "</td></tr>");

Your code is a bit irrelevant to the question you're asking. Your error has already been fixed by previous answers. But I will try to expand the asnwer further. If you wish to pass some value from C# to JavaScript, there're different methods.
1) You could make a protected method in a codebehind file and call it from your .aspx file, like
my.aspx
<script type="text/javascript">
var x = '<%= GetMyValue() %>';
DoFooWithX(x);
</script>
my.aspx.cs
protected string GetMyValue()
{
return "example";
}
2) If you wish to execute some JavaScript once page finishes loading, you could also do it from your codebehind like this
my.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string myScript = string.Format("myVar = '{0}';", GetMyVarValue());
ScriptManager.RegisterStartupScript(this, this.GetType(), "MyVarSetter", myScript, true);
}
private string GetMyVarValue()
{
return "example";
}

Related

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%>");
}

Refresh GridView from ClientSide (Javascript) in asp.net

I have added the Gridview control on a webPage.
I am deleting any row (one row at a time) by calling PageMethod as follow:
<script type="text/javascript">
function Delete_Row(){
PageMethods.DeleteRow(row_id, GetTimeCallback, ErrorHandler, TimeOutHandler);
}
GetTimeCallback = function (result)
{
if (result) {
alert('Row is deleted');
// I want to refresh the Gridview here
}
}
<script type="text/javascript">
where "row_id" is primery key of the row.
It shows the alert perfectly but does not refresh the Gridview with one less deleted row.
what code should i write to Update the gridview?
NOTE: I dont want to refresh entire page.
Write CallBack Function to acheive this...You can find the Callback Functionality at http://msdn.microsoft.com/en-us/library/ms178208 and http://msdn.microsoft.com/en-us/library/ms178210
Edit:-
protected void Page_Load(object sender, EventArgs e)
{
String cbReference =Page.ClientScript.GetCallbackEventReference(this,
"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
System.IO.StringWriter strDataGridHtml= new System.IO.StringWriter();
public void RaiseCallbackEvent(String eventArgument)
{
string idToBeDeleted=eventArgument;
//Write deleteCode
//DataBind the Grid
HtmlTextWriter htwObject = new HtmlTextWriter(strDataGridHtml);
GridViewControl.RenderControl(htwObject);
}
public String GetCallbackResult()
{
return strDataGridHtml.ToString();
}
Now as you see this strDataGridHtml will be sent to Javascript Function ReceiveServerData...
<script type="text/ecmascript">
function ReceiveServerData(rValue)
{
document.getElementById("divIDWhichEncapsulategridView").innerHTML = rValue;
}
</script>
Hope this Will Help you..As i don't i have your full code i can't write the exact one...but this should give you some idea on how to proceed...And also please go through the "CallBack" Functionality in order to understand this functionality to the fullest..

how to get client side confirm box value to make server side operations?

I am using Client script for confirm message box as follows
string script = "fadeScript";
ScriptManager.RegisterClientScriptBlock(this.Page, script.GetType(), "Script", "Closewindow();", true);
java script function:
<script type="text/javascript">
function Closewindow() {
var Result = confirm("Are you sure want to delete?");
alert(Result);
if (Result == true) {
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
alert(txtConfirmresult.value);
return true;
}
else
{
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
alert('BYE');
return false;
}
}
</script>
I want to use the script return value in .cs file to excite procedure if it returns true. if it return false i have to stay on that particular page only. plz kindly help me on this
You can use __doPostBack(target, argument) to post back to the server. You can then evaluate __EVENTTARGET and __EVENTARGUMENT in the post data to see what you sent back and perform logic appropriately. Here is a link that provides a little more in depth information.
A quick example:
Script/Client side:
<script type="text/javascript">
function Closewindow() {
var Result = confirm("Are you sure want to delete?");
alert(Result);
if (Result == true) {
var txtConfirmResult = document.getElementById('txtConfirmresult');
txtConfirmResult.value = Result;//assigning to hidden text box
alert(txtConfirmresult.value); //displaying for debug purposes
__doPostBack( 'txtConfirmresult', Result ); //sending back to server.
return true;
}
else
{
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
alert('BYE');
return false;
}
}
C#
protected void Page_Load(object sender, EventArgs e)
{
string target = Request["__EVENTTARGET"];
string argument = Request["__EVENTARGUMENT"];
if (target != null && target.Equals( "txtConfirmresult" ) )
{
this.DoSomeGreatServerSideProcessing(argument);
}
}
Updated to add slightly more correct variable names, but should work with your existing codebase assuming your script was working. I would be very careful using txtConfirmresult as your ID as that will only work if runat="server" is not set on the textbox. If that is the case, the ID will be prepended to denote container hierarchy.
I would suggest naming your "callbacks" very well, such as:
Script/Client side:
<script type="text/javascript">
function Closewindow() {
var Result = confirm("Are you sure want to delete?");
document.getElementById('txtConfirmresult').value = Result;//assigning to hidden text box
if (Result) {
__doPostBack( 'UserConfirmedFormSubmission', "CloseWindow" ); //sending back to server.
return true;
}
else
{
return false;
}
}
C#
protected void Page_Load(object sender, EventArgs e)
{
string target = Request["__EVENTTARGET"];
string argument = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(target) && target.Equals("UserConfirmedFormSubmission"))
{
if ( !string.IsNullOrEmpty(argument) && argument.equals("CloseWindow"))
{
this.HandleUserRequestedCloseWinow();
}
}
}

open page in new tab asp.net [duplicate]

This question already has answers here:
Response.Redirect to new window
(20 answers)
Closed 7 years ago.
I am writing a project using ASP.NET C#.
I want to implement linkbutton click event to open new page in a new tab, but before I have to create new session variable. I have tried this:
protected void LinkButton_Click3(Object sender, EventArgs e)
{
string p_id = (sender as LinkButton).CommandArgument;
Session["p_id"] = p_id;
Response.Write("<script type='text/javascript'> window.open('details.aspx','_blank'); </script>");
}
But it doesn't work anyway.
Based on your comments, you should disable your popup blocker.
Try this, call this function on button click or document.ready only on page where you want to redirect from.
<script type="text/javascript">
function newTab()
{
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script
or add this to linkbutton html
OnClientClick="aspnetForm.target ='_blank';"
Sometimes it works for me to just declare whatever I would invoke dynamically from the administrated code into a javascript function and just call it from within with the
RegisterClientScriptBlock method in ClientScript class:
Daclare the window.open function:
<script type="text/javascript">
function SetRedirect(URI) {
window.open(URI, "Details", "menubar=no, location=no, resizable=yes, scrollbars=yes, status=yes, width = 1200, height = 600");
}
</script>
And from within the code behind class just a gateway caller to this function like:
void MessageGateway(string URI)
{
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"logCallBack", #"<script type=""text/javascript"">SetRedirect('" + URI + "');</script>");
}
And that's it, you may call this gateway with your stuff as normally you do,
MessageGateway(string.Format("../IRMQueryPO.aspx?id={0}", e.Item.Cells[2].Text));
You can try tweeking the "target" parameter with "_blank" in order to open a tab instead a window, it's just a matter of the flavor your solution points in.

Categories