javaScript with ASP - c#

I'm trying to realize little program in ASP, which count numbers with timer. I use this task with JavaScript and have some problems when I call it from sharp code. So, this code works good:
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function counter() {
var q = Number(document.getElementById("TextBox1").value);
var i = Number(document.getElementById("Text1").value);
if (i < q) {
i += 1;
document.getElementById("Text1").value = i;
setTimeout("counter()", 10);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True"></asp:TextBox>
<input id="Button1" type="button" value="button" onclick="counter()" />
<input id="Text1" name="Text1" type="text" value="0"/>
</div>
</form>
</body>
Random function generates value in Page_Load and put in TextBox1. In this code I used inputs for everything. But I want to use asp controls and then I tried to rewrite the same with and call script from sharp, but my code doesn't work:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Text1" runat="server" Text="0"></asp:Label>
</div>
</form>
</body>
and sharp code:
string str = "function counter() {
var q = Number(document.getElementById(\"TextBox1\").value);
var i = Number(document.getElementById(\"Text1\").value);
if (i < q) { i += 1; document.getElementById(\"Text1\").value = i;
setTimeout(\"counter()\", 10) } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "counter", str, true);
Button1.Attributes.Add("onclick", "counter()");
and this what I see in html output:
<script type="text/javascript">
//<![CDATA[
function counter() { var q = Number(document.getElementById("TextBox1").value); var i = Number(document.getElementById("Text1").value); if (i < q) { i += 1; document.getElementById("Text1").value = i; setTimeout("counter()", 10) } }//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAPaDIYgDxN4mARW8/nWYR/uESCFkFW/RuhzY1oLb/NUVM34O/GfAV4V4n0wgFZHr3e02FqXa4CDb/Y32Jm7yDyEftd8wArFmKGvvW1nftcl6Q==" />
</div>
<div>
<input name="TextBox1" type="text" value="1332073012" id="TextBox1" />
<input type="submit" name="Button1" value="Button" onclick="counter();" id="Button1" />
<span id="Text1">0</span>
</div>
</form>
</body>
I see script and button with onclick="counter()" method, but it doesn't work, and I don't know why. and I couldn't find the similar samples.

the problem has little to do with running the code on the server, and more to do with the change of the node Text1 from input to span.
first, change all references to Text1 to get the property innerHTML instead of value, second, add a return false to the click event so the form doesn't get submitted. Finally, you're missing a ; in the C# code block, and should invoke setTimer with a function, not a string.
the resulting code would look like this:
string str = "function counter() {
var q = Number(document.getElementById(\"TextBox1\").value);
var i = Number(document.getElementById(\"Text1\").innerHTML);
if (i < q) { i += 1; document.getElementById(\"Text1\").innerHTML = i;
setTimeout(function(){counter();}, 10); } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "counter", str, true);
Button1.Attributes.Add("onclick", "counter(); return false;");
BTW, if you can script it on the client side, you should. Writing javascript on the server side definitely violates the unobtrusive principle

Related

NullReferenceException while using findControl on HTML

while clicking on button it give me an error "System.NullReferenceException: Object reference not set to an instance of an object"
aspx Code
<body>
<form id="form1" runat="server">
<div id="choto">
</div>
<asp:Button ID="btn" runat="server" onclick="btn_Click" Text="Submit" />
</form>
</body>
JS code
<script type="text/javascript">
document.getElementById("choto").innerHTML = "<input name=txt1 type=\"text\" id=\"txt1\" ru" + "nat=\"server\" />";
</script>
C# code
protected void btn_Click(object sender, EventArgs e)
{
// HtmlInputText txt = new HtmlInputText();
HtmlInputText txt = (HtmlInputText)FindControl("txt1");
txt.Value = "Shakeel";
}
Simply put, the input with the id "txt1" is not an ASP.NET control, therefore ASP.NET cannot find it. ASP.NET controls must be defined on the server, or the framework won't know about them.
<body>
<form id="form1" runat="server">
<div id="choto">
<asp:TextBox ID="txt1" runat="server" style="display:none;" />
</div>
<asp:Button ID="btn" runat="server" onclick="btn_Click" Text="Submit" />
</form>
</body>
ASP.NET controls cannot be added via JavaScript, however, they can be made to be invisible/visible using JavaScript.
<script type="text/javascript">
document.getElementById('<%# txt1.ClientID %>').style.display = "block";
</script>

How to retrieve binarydata source of an image in asp.net

I want to get image preview before uploading any image in my asp.net webform. I am doing this by the following code. But after clicking Save button I want to upload the image to the server. In my codebehind I am getting src="" for <img>. What can I do to get the binarydata back to save my file.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.10.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function showMyImage(fileInput) {
var files = fileInput.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var link = $(fileInput).siblings('.thumb').attr('src');
alert(link);
var img = document.getElementById("thumbnil");
img.file = file;
var reader = new FileReader();
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<input type="file" accept="image/*" onchange="showMyImage(this)" />
<br />
<img id="thumbnil" class="thumb" style="width: 20%; margin-top: 10px;" src="" alt="image" runat="server"/>
<asp:Button runat="server" Text="Save" OnClick="Unnamed_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Thanks in advance..
### Undated whole Answer ###
Option 1:
dont read the img-tag src-attribute, the client cant update it on server side and it wont be "post-back". use an input field like this
<form...>
...
<input class="image-data" type="hidden" id="imageString" runat="server" />
...
</form>
and in the Js-Code add this dataurl as value of this field.
...
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
//... add this, it's searches for the input-field, to be able to post the String to the Server
$(".image-data").val(e.target.result);
};
...
Update:
On the Server you can read the Data like this.
string imageData = imageString.Value;
Option 2:
you could also do this:
alter your asp.net-file
<!-- add enctype=... -->
<form id="form1" runat="server" enctype="multipart/form-data">
...
<!-- add name=... -->
<input type="file" accept="image/*" onchange="showMyImage(this)" name="uploadImage" />
...
in the Codebehind:
HttpPostedFile imageFile= Request.Files["uploadImage"];
if (imageFile && imageFile.ContentLength > 0)
{
// ... Use the imageFile variable as you please
}
Which Option depends, what you want to do with the data.

Display Dialog Box When User Meets MaxLength of TextBox

I have a asp.net C# application. I have a TextBox that has a MaxLength set of 3000. When the user reaches the maxlength of 3000 I want a JavaScript dialog box to open and alter the user of this. I can't figure out how to do it. Can anyone help me? Thanks.
From aspdotnet-suresh:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Limit the number of characters in textbox or textarea</title>
<script type="text/javascript">
function LimtCharacters(txtMsg, CharLength, indicator)
{
chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength)
{
txtMsg.value = txtMsg.value.substring(0, CharLength);
}
}
</script>
</head>
<body>
<div style="font-family:Verdana; font-size:13px">
Number of Characters Left:
<label id="lblcount" style="background-color:#E2EEF1;color:Red;font-weight:bold;">3000</label><br/>
<textarea id="mytextbox" rows="5" cols="25" onkeyup="LimtCharacters(this,3000,'lblcount');"></textarea>
</div>
</body>
</html>
You can use the TextChanged event of your TextBox for this. Inside your handler, you can simply check the length of the TextBox.Text property, and display a MessageBox if it reaches the maximum length like so:
Response.Write(string.Format("<script>alert('{0}');</script>", message));
You can restrict the number of characters with this JavaScript
<script language="javascript" type="text/javascript">
function limitText(Field, limitNum) {
if (Field.value.length > limitNum) {
Field.value = Field.value.substring(0, limitNum);
}
}
</script>
<asp:FormView runat="server">
<ItemTemplate>
<b>Something</b>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" onKeyDown="limitText(this,3000);"
onKeyUp="limitText(this,3000);"></asp:TextBox>
</EditItemTemplate>
</asp:FormView>
Or to Display alert,
<input type="text" onkeydown="return testLength()" id="txtBox" />
function testLength(){
var e = document.getElementById('txtBox');
if(e.value.length>6)
{
alert('you have entered more than 3000 characters');
// Set value back to the first 6 characters
e.value = e.value.substring(0, 3000);
}
return true;
}

Return lat and long values of user's current location to be used in a sql query

I am using HTML5 geolocation to obtain a users current location & display this on a google map. However I also want to return the lat and long values of this location and pass these values to a SQL datasource query. I want a lat variable and and a long variable to pass through. To get the lat I am simply assigning var jsVar = position.coords.latitude but this is not returning anything. I realise that I should be using hiddenfields to achieve to send the var to the server but am not totally sure how exactly to do it when there is more than one hiddenfield. Any help would be really appreciated. Here is what I have:
Javascript
function SetHiddenVariable() {
var jsVar = position.coords.latitude;
// Set the value of the hidden variable to
// the value of the javascript variable
var hiddenControl = '<%= inpHide.ClientID %>';
document.getElementById(hiddenControl).value = "Latitude = " + jsVar;
}
ASP.NET
<body onload="SetHiddenVariable()">
<form id="form1" runat="server">
<div>
<input id="inpHide" type="hidden" runat="server" />
<asp:TextBox ID="txtJSValue" runat="server"></asp:TextBox>
<asp:Button ID="btnJSValue"
Text="Click to retrieve Javascript Variable"
runat="server" onclick="btnJSValue_Click"/>
</div>
</form>
</body>
Code Behind C#
protected void btnJSValue_Click(object sender, EventArgs e)
{
txtJSValue.Text = inpHide.Value;
}
you could just concatinate the data on the client side (use a comma or some other delimiter that makes sense to you and then just separate on the server side. You would only need to use one variable in that case.
Here is the html way of doing this which should get you started. You'll just need to wire your button click event and turn the inputs into server side controls. Good luck!
<!DOCTYPE html>
<html>
<head>
<script>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
}
function success(position) {
document.getElementById("lat").value = position.coords.latitude;
document.getElementById("long").value = position.coords.longitude;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Lat: <input id="lat" type="text" />
Long: <input id="long" type="text" />
</div>
</form>
</body>
</html>

fileupload's upload button works different in IE and Chrome

For those who worked with bootstrap, knows it does not support input type = file, so I hide the asp:fileupload using jQuery (after document ready), and have and for the solution (as you can see from the code
<script type="text/javascript">
$(document).ready(function ()
{
$('#columnSelect').change(function ()
{
getImportColumnOrder();
});
// change file upload style similiar to bootstrap style
//$('#uploader').hide();
$('#uploader').change(function ()
{
var val = $(this).val();
var file = val.split(/[\\/]/);
$('#file').val(file[file.length - 1]);
});
});
function getImportColumnOrder()
{
var order = '';
$('#selectOrer').val('');
$('select', $('#MappingTable')).each(function ()
{
order += $(this).prop('selectedIndex') + ',';
});
$('#selectOrder').val(order.substr(0, order.length - 1));
}
</script>
<div class="span12">
<asp:DropDownList ID="ddl_DBTableList" runat="server" CssClass="combobox" Style="display: inline">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="Import_Test">Import_Test</asp:ListItem>
</asp:DropDownList>
<asp:FileUpload ID="uploader" runat="server" CssClass="btn" />
<div class="input-append" style="display: inline;">
<input id="file" class="input-medium" type="text" />
<a class="btn" onclick="$('input[id=uploader]').click();">Select File</a>
</div>
<p />
<div>
<asp:Button ID="btn_uplaod" runat="server" OnClick="doUpload" Text="Upload" CssClass="btn" />
</div>
<p />
<asp:Label ID="result" runat="server" ForeColor="Red"></asp:Label>
<p />
<asp:Label ID="data" runat="server" BackColor="#CCCCCC"></asp:Label>
<p />
<asp:Button ID="btn_import" runat="server" Text="Next" OnClick="doImport" OnClientClick="getImportColumnOrder();return true;" Visible="false" CssClass="btn btn-success" />
</div>
Steps are click on the "Select File", a file chooser popped up for file selection. After double clicked a file, the file location gets displayed in , and also the asp fileupload control.
In Chrome and FF, when I clicked btn_uplaod (button), it runs as supposed. In IE, it will clear the fileupload's content and does nothing (a client side action) and will not do any postback.
If this is a program problem, then maybe Chrome and FF will not run correctly. I'm suspecting is there anything that I need to add to make IE run as suppose to?
image after click upload (IE), (Browse link is cleared)
image after click upload (Chrome), (Run as supposed to)
thanks!
I've made a simple version for those of you who wants to try on Visual studio:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="postback_problem.aspx.cs" Inherits="postback_problem" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="uploader" runat="server" CssClass="btn" /> <div> <input id="file" class="input-medium" type="text" /> <a onclick="$('input[id=uploader]').click();">Select File</a> </div> <p /> <div> <asp:Button ID="btn_uplaod" runat="server" OnClick="doUpload" Text="Upload" CssClass="btn" /> </div> <asp:Label ID="result" runat="server"></asp:Label> </div> </form> </body> </html>
and
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class postback_problem : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void doUpload(object sender, EventArgs e) { result.Text = "no problem!"; } }

Categories