Get client-side value to server-side ASP.NET - asp.net

I tried to pass a variable from the client side to server side using HiddenField like in this example.
What I have tried so far:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type ="text/javascript">
<script type ="text/javascript">
function passValue() {
document.getElementById('<%=HiddenField1.ClientID%>').value = "some stuff";
}
window.onload = passValue;
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="HiddenField1" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick ="passValue()"/>
</div>
</form>
</body>
</html>
On the server side I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
string a, b;
if (IsPostBack)
{
Response.Write("The input value is: " + HiddenField1.Value.ToString());
a = HiddenField1.Value.ToString();
}
else
{
Response.Write("The input value is: " + HiddenField1.Value.ToString());
b = HiddenField1.Value.ToString();
}
}
When my page opens I expect to see on it the message: "The input value is: some stuff". The message appears only if I press the button because only in this case the IsPostBack becomes true.
What should I do so get the message without pressing the button? Thanks in advance!

Related

HttpUtility.HtmlEncode() do not work in asp.net TextBox control?

My code below:
Test.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="text" value="<%=HttpUtility.HtmlEncode(ab)%>" runat="server"/>
</form>
</body>
</html>
Test.cs:
public partial class Test: System.Web.UI.Page
{
public string ab;
protected void Page_Load(object sender, EventArgs e)
{
ab = "<script>alert('111');</script>";
}
}
After running the test.aspx page,the textbox value is <%=HttpUtility.HtmlEncode(ab)%>
But remove the runat="server" string show correct!
When you do a runat="server" on a control, it becomes a server control instead of a traditional HTML tag, so the attributes are dealt with on the server. Unfortunately, that means the inline script tags don't always do what you want them to do.
You can do a few things. Either leave off the runat="server" like you said, which makes it render exactly as you want, or set the value in the code:
myTextBox.Value = "whatever";
You can also use data binding, but it's kind of ugly:
<input id="myTextBox" runat="server" type="text"
value='<%# HttpUtility.HtmlEncode("someString") %>' />
protected void Page_Load(object sender, EventArgs e) {
myTextBox.DataBind();
}

Validator causes improper behavior for double click check

I have following script to prevent a button from submitting twice by double clicking. It works fine.
But the scenario gets clumsy when I added a Required Field validator. If I try to submit with a blank value in textbox, the validator fires. But when I entered value in textbox and try to submit again it does not do a postback.
I understand the reason, in the first button click itself, the variable isActionInProgress is set as 'Yes' irrespective of the validation error.
What is the best way to overcome this challenge?
MARK UP
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var isActionInProgress = 'No';
$('.myButton').click(function (e) {
if (isActionInProgress == 'No') {
isActionInProgress = 'Yes';
}
else {
e.preventDefault();
//alert('STOP');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:Button ID="Button1" CssClass="myButton" runat="server" Text="Submit" ValidationGroup="ButtonClick"
OnClick="Button1_Click" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtEmpName"
runat="server" ErrorMessage="RequiredFieldValidator" ValidationGroup="ButtonClick" Text="*"></asp:RequiredFieldValidator>
</div>
</form>
</body>
REFERENCES
Page_ClientValidate is validating multiple times.
Hide redundant error message in ASP.Net ValidationSummary
MSDN - ASP.NET Validation in Depth
I think somthin like this:
$('.myButton').click(function (e) {
if(Page_IsValid){
if (isActionInProgress == 'No') {
isActionInProgress = 'Yes';
}
else {
e.preventDefault();
//alert('STOP');
}
}
});

Returning javascript in an ASP.NET ajax postback fails, but works fine on initial page load

I have a standard webpage containing an UpdatePanel, and a button. Upon loading the page some javascript is set and the page renders a chart (using Highcharts from here http://www.highcharts.com/products/highcharts).
When I reload the UpdatePanel using a button, dropdown etc the chart does not re-render.
For brewity I have shortened the code, but normally I have an UpdatePanel with a dropdown where users can select various charts, then data is fetched from a database and the results are sent back to the page.
Can anybody explain why it does not work / load the chart when I click on the button - and how to fix it?
The chart can be download here: http://www.highcharts.com/products/highcharts - simply add this to a folder called /js/highcharts.js
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="false" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string jschart = "var chart;$('" + up1.ClientID + "').ready(function() {chart = new Highcharts.Chart({"
+ "title: { text: 'Traffic',x: 0, style: {fontSize:'13px'} },"
+ "chart:{renderTo: 'container', defaultSeriesType: 'column'},";
litChartData.Text = String.Format("{0} {1}", jschart, getData());
}
private string getData()
{
// this is normally coming from a database...
return "xAxis:{title:{text:'Date'}, type:'datetime'}, yAxis:{title:{text:'Hits'}},"
+ "series: [{ name:'Impressions',type:'column',"
+ "data: [ "
+ "[Date.UTC(2011,7,18),13],"
+ "[Date.UTC(2011,7,24),21],"
+ "[Date.UTC(2011,8,30),60]]"
+ "}] }) });";
}
</script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="/js/highcharts.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scr" />
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<script type="text/javascript">
<asp:Literal ID="litChartData" runat="server" />
</script>
<div id="container" style="width:700px;height:300px;margin:0 auto;background-color:#eee"></div>
<center><asp:Button ID="btn" runat="server" Text="Ajax postback" /></center>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
the chart is rendered on the client side upon jquery's Ready event, but the event is not re-fired upon ajax calls. the solution might be emitting different scripts depending on whether the request is initial or subsequent one (ajax).
on initial call just emit the script you have in jschart var.
on subsequent calls emit the same script but without wrapping it into Ready event binding.
UPDATE:
i totally forgot update panel does not execute nested scripts after updating.
the solution for that is registering scripts via script manager. try the following code. note there is no script literal in the update panel anymore.
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="false" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string jschart =
"if (window.chart) { window.chart.destroy(); }" +
"window.chart = new Highcharts.Chart(" +
"{title: { text: 'Traffic',x: 0, style: {fontSize:'13px'} }," +
"chart:{renderTo: 'container', defaultSeriesType: 'column'}," +
getData() +
"});";
ScriptManager.RegisterStartupScript(this, this.GetType(), "chart", jschart, true);
}
private string getData()
{
// this is normally coming from a database...
return
"xAxis:{title:{text:'Date'}, type:'datetime'}, "
+ "yAxis:{title:{text:'Hits'}},"
+ "series: [{"
+ "name:'Impressions',"
+ "type:'column',"
+ "data:"
+ "[[Date.UTC(2011,7,18),13],"
+ "[Date.UTC(2011,7,24),21],"
+ "[Date.UTC(2011,8,30),60]]"
+ "}]";
}
</script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="/js/highcharts.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scr" />
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<div id="container" style="width:700px;height:300px;margin:0 auto;background-color:#eee"></div>
<center><asp:Button ID="btn" runat="server" Text="Ajax postback" /></center>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

jquery drop down for selecting multiple values

i want to develop dropdown inside a check box . this url shows me how to do it.
http://dropdown-check-list.googlecode.com/svn/trunk/demo.html
but the code isnt given how to implement it in project.
i need to bind my datatable to this dropdow.
and once user selects a value and clicks on the button in .cs file i should be able to get all these values
if any one knows how to slove this issue let me know
thank you
This is a jquery plugin that does the transformation client side. You haven't tagged your question to indicate what server side technology you are using, but from your description I infer it is ASP.NET.
Here's a sample page I've setup illustrating how to achieve the functionality you are looking for:
<%# Page Language="C#" %>
<%# Import Namespace="System.Linq" %>
<script type="text/C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
listBox.DataSource = new[] { "Aries", "Taurus", "Gemini" };
listBox.DataBind();
}
}
protected void BtnClick(object sender, EventArgs e)
{
var selectedItems = (from item in listBox.Items.Cast<ListItem>()
where item.Selected
select item.Text).ToArray();
result.Text = "You selected: ";
result.Text += string.Join(",", selectedItems);
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript" src="scripts/ui.core.js"></script>
<script type="text/javascript" src="scripts/ui.dropdownchecklist.js"></script>
<script type="text/javascript">
$(function() {
$('.listBox').dropdownchecklist();
});
</script>
<link rel="stylesheet" href="css/ui.dropdownchecklist.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="listBox" runat="server" SelectionMode="Multiple" CssClass="listBox" />
<asp:LinkButton ID="btn" runat="server" Text="Click me" OnClick="BtnClick" />
<asp:Label ID="result" runat="server" />
</div>
</form>
</body>
</html>

ASP.Net Checkbox value at postback is wrong?

We have a checkbox that is initially disabled and checked. It is then enabled on the client side through javascript. If the user then unchecks the box and presses the button to invoke a postback, the state of the checkbox remains as checked on the server side. This is obviously undesirable behaviour. Here is an example.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="testcb.aspx.cs" Inherits="ESC.testcb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function buttonClick() {
var cb = document.getElementById('<%= CheckBox1.ClientID %>');
cb.disabled = false;
cb.parentNode.disabled = false;
}
</script>
<div>
<asp:CheckBox ID="CheckBox1" runat="server" Checked="true" Enabled="false" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="buttonClick(); return false;" />
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="button2Click" />
</div>
</form>
</body>
</html>
And the Server-side code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ESC
{
public partial class testcb : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void button2Click(object sender, EventArgs e)
{
string h = "";
}
}
}
So we break at the "string h" line and check the value of CheckBox1.Checked. It is true, even if it is unchecked on the form.
This is a known problem with ASP.NET - for some reason ASP.NET won't update a checkbox on postback if it was disabled during page load and not checked for postback. I don't know exactly why that is though - if you make the checkbox unselected by default and select it, the value is changed on the server correctly.
The workaround is to add a hidden field to the page that represents the state of the checkbox, then update the field's value to "ON" or "OFF" for example, whenever the checkbox is clicked.
Then on the server you check the value of the hidden field, not the checkbox itself, as the hidden field is always posted.
I had a similar problem to this where the Checked property of the CheckBox object was not being updated correctly, to get the actual posted value you can check:
Request.Form[CheckBox1.UniqueID]
it will be 'on' if the box is checked and null if not.
Since you're already using Javascript to manipulate the controls state in the browser, I suggest you just disable the checkbox on the page load event in stead. Then your postbacks will work just fine...
<head>
<script type="text/javascript">
function buttonClick() {
var cb = document.getElementById('<%= CheckBox1.ClientID %>');
cb.disabled = false;
cb.parentNode.disabled = false;
}
</script>
</head>
<body onload="document.getElementById('<%= CheckBox1.ClientID %>').disabled = true;">
<form id="form1" runat="server">
<div>
<asp:checkbox id="CheckBox1" runat="server" checked="true" />
<asp:button id="Button1" runat="server" text="Button" onclientclick="buttonClick(); return false;" />
<asp:button id="Button2" runat="server" text="Button2" onclick="button2Click" />
</div>
</form>
</body>
I may not understand the problem correctly, but can't you just use the Form from the Request to retrieve the CheckBox value? So in button2Click() in the code behind file you'd do this:
Request.Form[CheckBox1.UniqueID]
You can use something like this.
if ((Request.Params["Checkbox1"] ?? "").ToString() == "on")
If it isn't checked it won't pass it in the first place, but this should account for that.
Here is an alternative solution if you need to avoid recompiling your source code.
It just enables the checkbox for a split second before submitting the form.
1: Add the following parameter to your submit button:OnClientClick="EnableCheckbox()"
2: Add this simple function somewhere on the page to enable it
<script>
function EnableCheckbox() {
document.getElementById("<%=chkMyCheckbox.clientID %>").disabled = false;
}
</script>

Resources