Call Public variable of C# in javascript? - c#

My Problem is I am try to call Public variable in Code Behind From JavaScript function
I try To Do This :
In Code Behind Section:
public string str ="TEST";
In JavaScript Section:
<script type="text/javascript" language="javascript">
function funDoSomething()
{
var strMessage = '<%= str%>';
alert( strMessage );
}
</script>
Any Suggestion?

<script type="text/javascript" language="javascript">
function funDoSomething()
{
var strMessage = <%= "'" + str + "'"%>;
alert( strMessage );
}
</script>
Ugly but should work.

I found the answer and it is Like this
In JavaScript Section:
<script type="text/javascript" language="javascript">
function funDoSomething()
{
var strMessage = "<%=str%>";
alert( strMessage );
}
</script>
This Work With Me :)

Related

$(document).ready() is not working after coming back from another page

I am developing an application in asp.net using c#. In my page I have done ajax call to load the page with html. The html code is coming from the database. This ajax call is written in the document.ready() function. When I am first time loading the page its working fine. When I am going to another page, that is also working fine. But when I am trying to coming back from that page then the document.ready() is not working. For that reason the html code is also not getting populated. How can I solve this issue please help me out from here.
Document.ready() code is as follows:
$(document).ready(function () {
tempName = GetParameterValues("templateName");
//alert(tempName);
if (tempName != "" || tempName != null) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "DesignCenter_Static.aspx/loadTemplatePackage",
data: "{'template_name':'" + tempName.toString() + "'}",
dataType: "JSON",
success: function (data) {
var temp_data = data.d.toString();
var temp_arr = new Array();
temp_arr = temp_data.split("|");
$("#divTemplateLayout").html(temp_arr[0].toString());
$("#inputForm").html(temp_arr[1].toString());
$("#divButtonSet").html(temp_arr[2].toString());
$("#inputForm").find('[id^="txt"]').each(function () {
var cName, labelControlName, divControlName, resizeClassName, existingClassName, txtName;
txtName = $(this).attr("id");
cName = txtName.slice(3, txtName.length);
divControlName = "lbl" + cName;
$("#" + divControlName + "").resizable({
maxWidth: 300,
minHeight: 16,
minWidth: 50,
containment: "parent",
autoHide: true,
handles: "n, e, s, w, ne, se, sw, nw"
});
$("#" + divControlName + "").draggable({ cursor: 'move', containment: ".setLimit" });
});
},
error: function (result) {
alert("Error");
}
});
}
$("#ddlZoom").val("100%");
currentZoomLevel = $("#ddlZoom").val();
fillInitialDesignStudio();
});
Back Button Code of another page is as follows:
$(function () {
$("#btnBack").click(function () {
var resPage = GetParameterValues("responsePage");
var tempName = GetParameterValues("templateName");
window.location.href = resPage + "?returnPage=BC_Proof.aspx&templateName=" + tempName;
});
});
Master page code for adding jquery library:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.placeholder.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/holder.js"></script>
<%--<script src="js/colpick.js" type="text/javascript"></script>--%>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript" src="js/placeholders.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="js/spectrum.js"></script>
<script type="text/javascript" src="js/scolor.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script src="js/ui/jquery.ui.core.js"></script>
<script src="js/ui/jquery.ui.widget.js"></script>
<script src="js/ui/jquery.ui.button.js"></script>
<script src="js/ui/jquery.ui.position.js"></script>
<script src="js/ui/jquery.ui.menu.js"></script>
<script src="js/ui/jquery.ui.autocomplete.js"></script>
<script src="js/ui/jquery.ui.tooltip.js"></script>
Thanks in advance
issue is templateName not getting properly , Check Ajax data,
data: "{'template_name':'" + tempName.toString() + "'}",
Your BackButton Code:
var tempName = GetParameterValues("templateName");
use GetParameterValues("template_name"); instead of GetParameterValues("templateName");

Save the <LI> Class value on Site.master postback event

I wanted to change class of <LI> on click, which I managed to do with jquery (I'm Newbie in jquery)
The Code:
<script type='text/javascript'>
$(function () {
$('#Mymenu li').click(function () {
$('li.active').removeClass('active');
$(this).addClass('active');
});
});
</script>
It's work Perfectly. That Jquery code above removes class of an li and assign it to other, but once redirect/postback occurs its lost the value and back to the default value.
any Idea thanks
You can store value of currently selected li in cookie,localStorage or window hash and retrive the value on page reload.
check out window hash example
<script type="text/javascript">
$(function () {
$('li.active').click(function () {
//tweak this line
window.location.hash = $(this).attr('id');
$("li.active").removeClass("active")
$(this).addClass('active');
});
var hash = window.location.hash;
$("#"+hash).removeClass("active")
$("#"+hash).addClass('active');
});
</script>
Update
Check out the complete example
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(function () {
$('li').click(function () {
//tweak this line
window.location.hash = $(this).index();
$("li.active").removeClass("active")
$(this).addClass('active');
});
var suffix = window.location.hash.match(/\d+/);
$("li:eq(" + suffix + ")").removeClass("active")
$("li:eq(" + suffix + ")").addClass('active');
});
</script>
<style>
.active {
color: red;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul>
<li>A
</li>
<li>B
</li>
<li>C </li>
<li>D
</li>
</ul>
</div>
</form>
</body>
</html>
Thanks to all who comments to my question, I got the better solution of this issue base on this site:
ASP.NET C# With list navigation how to set id=“current” on active navigation page?
Based on the my researched I need to set it manually in the Page_Load event:
here the code
protected void Page_Load(object sender, EventArgs e)
{
SetCurrentPage();
}
private void SetCurrentPage()
{
var pageName = GetPageName();
switch (pageName)
{
case "home.aspx":
HomeLink.Attributes["class"] = "current";
break;
case "Calendar.aspx":
CalendarLink.Attributes["class"] = "current";
break;
case "Bill.aspx":
BillLink.Attributes["class"] = "current";
break;
}
}
private string GetPageName()
{
return Request.Url.ToString().Split('/').Last();
}
it's working perfectly right now.

Copy text to clipboard using Zero Clipboard in asp.net

I am trying to use Zero *Clipboard* to copy text from Textbox to Clipboard when client clicks a Button. I am trying this for many days but no luck to make this work.
In Scenario, i have one Textbox which render data from the Database. I have one Button which when client clicks should copy text of the Textbox. I have tried following but its not working.
Some help will be appreciated.
<script type="text/javascript" src="/Scripts/ZeroClipboard.js"></script>
<script type="text/javascript">
ZeroClipboard.setMoviePath('/Scripts/ZeroClipboard.swf');
</script>
<script>
function test() {
ZeroClipboard.setMoviePath('/Scripts/ZeroClipboard.swf');
//create client
var clip = new ZeroClipboard.Client();
//event
clip.addEventListener('mousedown', function () {
clip.setText(document.getElementById('TextBox2').value);
});
clip.addEventListener('complete', function (client, text) {
alert('copied: ' + text);
});
//glue it to the button
clip.glue('d_clip_button');
}
</script>
<asp:TextBox ID="TextBox2" runat="server" BorderStyle="None" Enabled="False" Font-Size="Medium" ForeColor="Black" Width="213px"></asp:TextBox>
<asp:Button ID="d_clip_button" runat="server" Text="Copy" OnClientClick="javascript:test();" />
<html>
<body>
<button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">
Copy to Clipboard</button>
<script src="ZeroClipboard.js"></script>
<script src="main.js"></script>
</body>
</html>
//In Main.js file
// main.js
var clip = new ZeroClipboard( document.getElementById("copy-button"), {
moviePath: "/path/to/ZeroClipboard.swf"
} );
clip.on( 'load', function(client) {
// alert( "movie is loaded" );
} );
clip.on( 'complete', function(client, args) {
this.style.display = 'none'; // "this" is the element that was clicked
alert("Copied text to clipboard: " + args.text );
} );
clip.on( 'mouseover', function(client) {
// alert("mouse over");
} );
clip.on( 'mouseout', function(client) {
// alert("mouse out");
} );
clip.on( 'mousedown', function(client) {
// alert("mouse down");
} );
clip.on( 'mouseup', function(client) {
// alert("mouse up");
} );
<html>
<body>
<script type="text/javascript" src="ZeroClipboard.js"></script>
<div id="d_clip_button" style="border:1px solid black; padding:20px;">Copy To Clipboard</div>
<script language="JavaScript">
var clip = new ZeroClipboard.Client();
var myTextToCopy = "Hi, this is the text to copy!";
clip.setText( myTextToCopy );
clip.glue( 'd_clip_button' );
</script>
</body>
</html>
First of all, you're trying to pick element by wrong id. Since you use webforms, correct way is:
getElementById('<%=TextBox2.ClientID%>')
Also, following unobtrusive js style good solution might look like:
$().ready(function () {
ZeroClipboard.setDefaults({ moviePath: "/Scripts/ZeroClipboard.swf" });
var clip = new ZeroClipboard(document.getElementById('YourButtonId')); //or '<%=YourButton.ClientID%>' if you use asp.net button
clip.on('complete', function (client, args) {
alert("Copied text to clipboard: " + args.text);
});
});
Also your button should have data attribute data-clipboard-target(actually there're three ways to do it). Setting data-attributes to webforms control is tricky, so you might want to avoid using asp.net button here and do it like:
<input type="button" value="clickme" id="YourButtonId" data-clipboard-target="<%=TextBox2.ClientID %>"/>
Enjoy!

jquery msgBox execution in code behind(c#)

I want to show a message box when user enters wrong ıd or password. I write following function to the .aspx file:
<script type="text/javascript">
function warningMessage() {
$.msgBox({
title: "Hatalı Giriş",
content: "Kullanıcı numarası ya da şifre hatalı...",
type: "error",
buttons: [{ value: "Ok" }]
});
}
</script>
and I write the following code to the aspx.cs file:
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "warningMessage ", "warningMessage()", false);
but this code does not work. Can you help me?
While using this plugin it is necessary to include 3 files:
<script src="Scripts/jquery-2.0.0.js" type="text/javascript"></script>
<script src="Scripts/jquery.msgBox.js" type="text/javascript"></script>
<link href="Styles/msgBoxLight.css" rel="stylesheet" type="text/css">
I used this code on client-side:
<script type="text/javascript">
function warningMessage() {
$.msgBox({
title: "Hatalı Giriş",
content: "Kullanıcı numarası ya da şifre hatalı...",
type: "error",
buttons: [{ value: "Okay"}]
});
}
</script>
On server-side:
Page.ClientScript.RegisterStartupScript(this.GetType(), null, "warningMessage();", true);
IT WORKS WELL FOR ME

C# WebForm - Set focus of textbox with Javascript

I have a Javascript that when i write in one textbox, it fills another textbox. But i need that the focus stay in a third textbox.
Actually, my code is:
<script type="text/javascript" language="javascript">
function SelectValue(source, eventArgs) {
document.getElementById('<%= txtCodeProduct.ClientID %>').value = eventArgs.get_value();
document.getElementById('<%= txtQuantity.ClientID %>').focus();
}
</script>
but the focus don't work...If i put an alert in a code, the focus work:
<script type="text/javascript" language="javascript">
function SelectValue(source, eventArgs) {
document.getElementById('<%= txtCodeProduct.ClientID %>').value = eventArgs.get_value();
document.getElementById('<%= txtQuantity.ClientID %>').focus();
alert("test");
}
How i resolve this without use alert ?
My textbox are in a form that uses update panel.
Thanks.
Try:
function SelectValue(source, eventArgs) {
document.getElementById('<%= txtCodeProduct.ClientID %>').value = eventArgs.get_value();
setTimeout( function(){
document.getElementById('<%= txtQuantity.ClientID %>').focus();
}, 0);
}
What version of Asp.Net do you use? otherwise you can use ClientIDMode
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx
<asp:TextBox ID="txtCodeProduct" runat="server" ClientIDMode="static" />
<asp:TextBox ID="txtQuantity" runat="server" ClientIDMode="static" />
I also recommend using jQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script type="text/javascript">
function SelectValue(source, eventArgs) {
$("#txtCodeProduct").val(eventArgs.get_value());
$("#txtQuantity").focus();
}
http://api.jquery.com/focus/

Categories

Resources