How to pass data between different c# and javascript - c#

I have an ascx page with a div, when the div is clicked it calls a JS function and send an int
//HTML
<div style="float: right; margin-right: 150px;" class="innerDivStyle"
onclick="userStartExtend(2)">
<h1 style="margin-top: 50px">Product</h1>
</div>
//JavaScript function
function userStartExtend(num) {}
I need to use the num from userStartExtend function in a c# (file/page/code). I thought about querystring - set in javascript code and get in c# (possible?). Any other ideas ??
To make things clear : the c# code and javascript code dont share the same page.

What one normally does in a case where he wants to pass something from Javascript to .NET he uses eventHandlers, just don't forget to add attributes runat="server" id="DivId" and event handler OnServerClick="DivHandler".
Example:
<div runat="server" id="DivId" OnServerClick="DivHandler" style="float: right; margin-right: 150px;" class="innerDivStyle" onclick="userStartExtend(2)" >
<h1 style="margin-top: 50px">Product</h1>
</div>
then on C# side
public void DivHandler(object sender, EventArgs e)
{
//here sender is your <div> and e is data about 'click' event.
}
UPDATE: It appears that OnServerClick does not work properly ether. Here is workaround
HTML:
<div runat="server" id="DivId" OnServerClick="testMe('param1')" style="float: right; margin-right: 150px;" class="innerDivStyle" onclick="userStartExtend(2)" >
<h1 style="margin-top: 50px">Product</h1>
</div>
JavaScript:
function testMe(params) {
var btnID= '<%=MyButton.ClientID %>';
__doPostBack(btnID, params);
}
Server-side Page_Load:
string parameter = Request["__EVENTARGUMENT"];
if (parameter == "param1")
MyButton_Click(sender, e);

Make your div server side
<div id="serverSideId" runat="server" />
In your C# code, Page_PreRender should have this
int myValue = 2;
serverSideId.OnClientClick = "userStartExtend(" + myValue.ToString() + ")";

Add a hidden Field control in your use control
<asp:HiddenField ID="hdnval" runat="server" Value="" Visible="false">
update your javascript function as this
function userStartExtend(num) {
var myHidden= document.getElementById('<%= hdnval.ClientID %>');
if(myHidden)
{
myHidden.value=num;
}
}
Now use can access this server control at code behind

Related

Textchange event not working

I am doing a preview of what I am currently typing in a web page using ASP.NET. What I am trying to achieve is that whenever I type or change text in the textbox, the <h3> or label element will also change and always copy what the textbox value is without refreshing the browser. Unfortunately I cannot make it work. Here is what I tried.
.ASPX
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
}
I Tried Adding Autopostback = true... but it only works and refreshes the page and i need to press tab or enter or leave the textbox :(
UPDATE: I Tried This - enter link description here But Still Doesnt Work :(
Just add this script function in your code and in body write onload and call that function.
Javascript:
<script type="text/javascript">
function startProgram() {
setTimeout('errorcheck()', 2000);
}
function errorcheck() {
setTimeout('errorcheck()', 2000);
document.getElementById("NewsTitlePreview").innerText = document.getElementById("Titletxt").value
document.getElementById("NewsContentPreview").innerText = document.getElementById("Contenttxt").value
}
</script>
<body onload="startProgram();">
<form id="form1" runat="server">
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" ></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</form>
</body>
You are right in your analysis of the behavior of the control (it only fires the event when you leave the control), even when you have AutoPostBack="True".
MSDN says it all:
The TextBox Web server control does not raise an event each time the user enters a keystroke, only when the user leaves the control. You can have the TextBox control raise client-side events that you handle in client script, which can be useful for responding to individual keystrokes.
So you either have to be satisfied with the current behavior, or set up some client side event handling to do some validation, etc. client side.
Download and include JQuery library. And also modify title and content textbox so they don't change their Id's
Title
<asp:TextBox ID="Titletxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" ClientIDMode="Static" runat="server"></asp:TextBox>
Then add this script and it will work.
<script>
$(document).ready(function () {
$('#Titletxt').on('input', function () {
$("#NewsTitlePreview").text($(this).val());
});
$("#Contenttxt").on('input',function () {
$("#NewsContentPreview").text($(this).val());
});
});
</script>
One of the best idea...
Just change your code to this. it works
ASPX
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
<div class="Padding10px">
<h1 class="Margin0px">Preview</h1>
<hr />
<p></p>
<h3 id="NewsTitlePreview" class="TextAlignCenter" runat="server">Title</h3>
<h5 id="NewsContentPreview" class="TextIndent50px TextAlignJustify" runat="server">Content</h5>
</div>
</div>
<div class="Width960px MarginLeftAuto MarginRightAuto MarginTop10px">
Title
<asp:TextBox ID="Titletxt" runat="server" OnTextChanged="Titletxt_TextChanged"></asp:TextBox>
Content
<asp:TextBox ID="Contenttxt" runat="server" onchange="Contenttxt_TextChanged"></asp:TextBox>
<asp:Button ID="Submit" runat="server" Text="Submit" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
.CS
protected void Titletxt_TextChanged(object sender, EventArgs e)
{
NewsTitlePreview.InnerText = Titletxt.Text;
UpdatePanel1.Update();
}
protected void Contenttxt_TextChanged(object sender, EventArgs e)
{
NewsContentPreview.InnerText = Contenttxt.Text;
UpdatePanel1.Update();
}
Try this it will work this how change event call using jquery dont forget to add google apis
<script>
$('#txtbox').change(function() {
alert("change Event");
});
</script>

How does my site know what button I clicked?

'
I have a problem with my site in ASP.NET. My applications contains a few buttons (imagebuttons) that are able to change. For example: When I press an empty button I want to be able to put a picture and a website in it. I've made this possible with a popupbox.
The problem where I'm running into:
When Im trying to give button 2 a image and a website, it gives button 1 a image and website because I told it in:
public partial class Ingelogd : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Image1_Click(object sender, ImageClickEventArgs e)
{
if (DropDown.SelectedItem.Value == "Youtube")
{
Btn_1.ImageUrl = "~/Images/Youtube.png";
Btn_1.PostBackUrl = ("http://www.youtube.com");
Btn_1.OnClientClick = "";
}
else
{
}
}
Now I actually want the same for Btn_2 , but then I have to write the exact same code but change Btn_1 to Btn_2. This is impossible to do because I want 19 website ( youtube but also facebook, twitter etc.) Im also going to have 19 buttons ( currently I only have Btn_1 and Btn_2). This would mean I have to make 19*19 = 361 pieces of code. I assume there is a way to make a sub program for this. My teacher also told me I could use cookies for the buttonclick, but I have no idea how to make a cookie with a Imagebutton.
What is the best solution to solve this problem?
I also have the ASP.NET Code here for you who wants to see that code aswell.
<title>Ingelogd</title>
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
<style type="text/css">
#popupBoxOnePosition{
top: 0; left: 0; position: fixed; width: 100%; height: 120%;
background-color: rgba(0,0,0,0.7); display: none;
}
.popupBoxWrapper{
width: 550px; margin: 50px auto; text-align: left;
}
.popupBoxContent{
background-color: #FFF; padding: 15px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Dit is de pagina als je ingelogd bent.
</div>
<div id="popupBoxOnePosition">
<div class="popupBoxWrapper">
<div class="popupBoxContent">
<h3>Instellingen</h3>
<p>Kies uit een van de volgende links.</p>
<asp:DropDownList ID="DropDown" runat="server">
<asp:ListItem >Select</asp:ListItem>
<asp:ListItem >Youtube</asp:ListItem>
<asp:ListItem >Facebook</asp:ListItem>
</asp:DropDownList>
<br />
<asp:ImageButton ID="Button1" runat="server"
OnClick="Image1_Click"/>
<br />
<asp:Button ID="Button_afsluiten" runat="server" Height="48px" OnClientClick="toggle_visibility('popupBoxOnePosition');return false;" Text="Afsluiten" />
</div>
</div>
</div>
<asp:ImageButton ID="Btn_1" runat="server" Height="48px" OnClientClick="toggle_visibility('popupBoxOnePosition');return false;"
ImageUrl="" />
<asp:ImageButton ID="Btn_2" runat="server" Height="48px" OnClientClick="toggle_visibility('popupBoxOnePosition');return false;"
ImageUrl="" />
</form>
</body>
</html>
You can try to add attributes to DropDownList and to use it. For example add two new attributes ImageUrl and SiteUrl. Your code should look:
protected void Image1_Click(object sender, ImageClickEventArgs e)
{
Btn_1.ImageUrl = DropDown.Attrubutes["ImageUrl"];
Btn_1.PostBackUrl = DropDown.Attrubutes["SiteUrl"];
Btn_1.OnClientClick = "";
}
I've never used asp, but most of those code is just plain c#, so I should be good.
Make 19 separate functions, one for each button, and dynamically add the Image and Url instead of using ifs:
protected void Image1_Click(object sender, ImageClickEventArgs e)
{
String val = DropDown.SelectedItem.Value;
Btn_1.ImageUrl = "~/Images/" + val + ".png";
Btn_1.PostBackUrl = "http://www." + val + ".com";
Btn_1.OnClientClick = "";
}
If you want 1 function for all buttons as well, you'll have to give all your buttons a Name and check the senders name inside the function.

Is there anyway to have an UpdatePanel update after a button click, but before the methods in the button click occur?

What I have is an ASP.NET 2.0 web application that allows the user to upload a .CSV
The html input type is submit.
I want to know if there is a way I can update my UpdatePanel that is below the input to show a little "Processing" .gif before my onserverclick method takes place.
I have tried putting a reference to another event at the beginning of that event, as well as other methods, but I'm getting no luck. From what I understand the method needs to finish before my UpdatePanel will refresh.
Here is some code for you guys
<div class=" content-div">
<input type="file" id="File1" name="File1" runat="server" />
Select file Type:
<asp:DropDownList ID="ddlfileupload" runat="server">
<asp:ListItem>CSV</asp:ListItem>
</asp:DropDownList>
</div>
<div class=" content-div">
<input type="submit" id="Submit1" value="Upload File" runat="server" onserverclick="Submit1_ServerClick"
style="border-top-style: groove; border-right-style: groove; border-left-style: groove;
border-bottom-style: groove" />
<asp:Label ID="Label6" runat="server" BorderColor="White" BorderStyle="None" Font-Bold="True"
Visible="False"></asp:Label>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
and the event behind the code:
protected void Submit1_ServerClick(object sender, EventArgs e)
{
AddProcessGif();
// Logic from submit button here that uploads .csv
}
AddProcessGif() is a method that programatically adds my .gif and stuff. And it works, I have seen it fire, but only after my upload finishes, which defeats the purpose.
I don't have a very well written application here and I'm pretty new to ASP.NET, so I am not sure how to effectively make a progress bar or anything like it.
Any advice would be appreciated
You can call a c# server side method from javascript.
what you need to do is add a scriptmanaget in your aspx page and set EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
also your C# method has to be a [WebMethod] like
[WebMethod]
public static string DoSomething(string str1, string str2)
{
string result = "This is concatenation of " + str1 + " and " + str2 + "'.";
return result;
}
and then add the javascript function in your aspx page to call C# server side DoSomething method
<head runat="server">
<title></title>
<script type="text/javascript">
function DoSomthing() {
var str1 = document.getElementById('<%=txtstr1.ClientID %>').value;
var str2 = document.getElementById('<%=txtstr2.ClientID %>').value;
//Here we call server side methode
PageMethods.DoSomeThing(str1, str2, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
Hope it helps

Binding mouseover event to asp.net repeater

I have an asp.net repeater that displays a title and and image.
The title is very long , so I want to display the title again on mouse over.
I tried to implement a mouse over but I have the following problem.
My display looks like this :
Repeater Element 1 Repeater Element 2
Title 1 Title 2
Image 1 Image 2
Now on doing a mouse over on Element1 , my mouse over displays Title1.
On doing a mouseover on Element2 , my mouse over displays Title1 again ,and I would like it to
display Title2 ? Can anyone point me on how i can achieve this.
My code is below :
<asp:Repeater ID="rptMonitorSummary" runat="server" OnItemDataBound="rptMonitorSummary_OnItemDataBound">
<ItemTemplate>
<asp:Panel ID="Pnl" runat="server" onmouseover="return showsamplepopup();" onmouseout="return hidesamplepopup();">
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">
<%# Eval("Name").ToString().Length > 9 ? (Eval("Name") as string).Substring(0, 9) : Eval("Name")%>
</h5>
<div id="popup" style="position: absolute; width: 80px; height: auto; background-color: Lime;
border-bottom: solid 3px gray; display: none; border-right: solid 3px gray; display: none;">
<%#Eval("Name")%>
</div>
<div class="center">
<asp:Image Width="50px" ID="btnPerformanceImage" runat="server" Height="28px"></asp:Image>
</div>
</li>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
The javascript functions are as follows :
function hidesamplepopup() {
document.getElementById('popup').style.display = 'none';
return false;
}
function showsamplepopup(e) {
e = (e) ? e : window.event;
var element = (e.target) ? e.target : e.srcElement;
var left = element.offsetLeft;
var top = element.offsetTop;
while (element = element.offsetParent) {
left += element.offsetLeft;
top += element.offsetTop;
}
document.getElementById('popup').style.display = 'block';
document.getElementById('popup').style.left = left;
document.getElementById('popup').style.top = top;
return false;
}
I do not know what is your requirement. It could have been a lot easier if you use jQuery tooltip.
This is just an alternative approach.
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function () {
$(document).tooltip();
});
</script>
<asp:Repeater ID="rptMonitorSummary" runat="server"
OnItemDataBound="rptMonitorSummary_OnItemDataBound">
<ItemTemplate>
<asp:Panel ID="Pnl" runat="server">
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header" title="<%# Eval("Name").ToString() %>">
<%# Eval("Name").ToString().Length > 9 ?
(Eval("Name").ToString()).Substring(0, 9) : Eval("Name")%>
</h5>
<div class="center">
<asp:Image Width="50px" ID="btnPerformanceImage"
runat="server" Height="28px"></asp:Image>
</div>
</li>
</asp:Panel>
</ItemTemplate>
</asp:Repeater>
Notice that getElementById will return the first element with that ID. And you're using the same ID for your Div's.
You should either use a different ID for each item of the repeater (generating different ID's for each of them), or change your logic to fetch them by some other property. I highly recommend using jQuery as well.
I would change the way which you are binding the events to elements, as your sample code doesn't use jQuery I'll assume you don't want it :)
First things first, you'll want to add a class to the asp:panel so that there will be some way of identifying and selecting all the instances. Also you'll want to use classes for your popups not IDs as IDs should be unique on a page.
then you can do something like:
var elements = document.querySelectorAll('.thatClassYouAdded'),
i = 0, l = elements.length;
for(;i<l;i++)
{
elements[i].addEventListener('mouseover', function(e) {
var popup = this.querySelector('.popup');
//do some stuff to popup
});
}
It's also important to note that querySelector is not supported in legacy browsers (see https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector for more info and support table) and older IEs (pre 9) use attachEvent instead of addEventListener which you may need to write additional code to support

Read label value in code behind

Am using the below code to assign the label text using javascript. It's working well. But i can't able to read the label text in code behind. Please help me to fix this issue.
Javascript:
==========
var lbl_total = document.getElementById('<%= lbl_total.ClientID %>');
lbl_total.innerHTML = '500';
c# code behid :
===============
string total = lbl_total.Text; //It always return "";
client side changes for label will not get reflected in server side as its data is not posted to server. So the solution is to take an input hidden control and set its value with label's updated value. Below is the sample code:
<script type="text/javascript">
$(document).ready(function() {
var total = 0;
$('#Button1').click(function() {
total += 150;
$("span[id$=lbl_TotalCount]").html(total);
$("input:hidden[id$=MyHidden]").val(total);
});
});
</script>
html
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
<asp:Button ID="btn_saveForm" runat="server" Text="save" CssClass="btnForm" OnClick="btn_saveForm_Click" />
<asp:Label ID="lbl_TotalCount" Style="color: #00e4ff; font-family: Arial; font-weight: bold;
text-decoration: underline" runat="server" Text="0">
</asp:Label>
<asp:HiddenField ID="MyHidden" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
full Article : Get label value in code behind whose text is changed via JavaScript/jQuery

Categories

Resources