Javascript value in asp

How to pass value to external javascript file using asp.net

I’m doing validation in asp.net through an external javascript file. How can I pass the value to the function which is in the external javascript file? my asp code is:

When I click this button it’s supposed to show an alert message, but it didn’t. Please tell me what I’m doing wrong. My Javascript code is:

function phonenumber(inputtxt) < var phoneno = /^\d$/; if(inputtxt.value.match(phoneno)) < return true; >else < alert("Not a valid Phone Number"); return false; >> 

Look at the JavaScript console. What errors do you get? (You have an obvious typo that it should alert you to)

Also, since your using asp.net why not used the regex validator? all asp validation is handled clientside by default ( EnableClientScript=»True» ).

2 Answers 2

another option: set the textbox ClientIDMode to Static and just reference the input field by ID as txtInput, this way you can avoid the name mangling and make your input fields more JS friendly such that this:

is rendered as: (note the id on the text input)

Also note that the button is rendered as a submit type, which will force a postback anyway. yiou may just want to use a plain html tag with a plain onclick=’phonenumber()’ to avoid postback because even if you choose to render the with attribute UseSubmitBehavior=»False» it will still inject a postback after your OnClientClick code.

function phonenumber() < var phoneNumText = document.getElementById('txtInput'); var phoneno = /^\d$/; if(phoneNumText.value.match(phoneno)) return true; else < alert("Not a valid Phone Number"); return false; >> 

Yes when i m using plain button and a textbox it works even when passing the argument. but when it comes to asp control ..nothing happens

Читайте также:  Classinform ru ksr kod html

@Abhay: that’s due to the asp:Button rendering as a submit type, the postback is stomping the JS call. You need to use an asp button type that does not render to a submit type button. The asp button controls are closely tied to the asp.net validation controls and they render a lot of their own javascript. It gets very complicated very quickly when you try to weave your own validation into the mix, I’ve found it best to either use the built in ASP validation, or use basic HTML and avoid ASP.NET validation completely. You can still trigger postbacks from JS via __doPostBack();

Источник

How to get value of application variable in JavaScript from asp.net?

You can make the variable public to access in javascript.

public string YourVar = "hello"; 

Note the value of the server side variable is substituted in generated html / javascript once the response is sent. If you want to access it from javascript after page is loaded then you might need to use ajax call to fetch value from server.

thanks for Reply me.My code is like Application[«Test»] = Some value.My Query is that i wants access value of this Application variables in javascript.How can i access it Please help me

The following gets the ClientID of the rendered control

//markup   //script var Members = < aTextBox: $("#"), bTextBox: $("#"), cTextBox: $("#") > 

Try the Sessions. Make a session in your class (I assume you have a General class)and use its reference to access it on any page you want. But remember you have to assign a value before using it.

below is a session of UserID.

public static int UserId < get < if (HttpContext.Current.Session["UserId"] != null) return Convert.ToInt32(HttpContext.Current.Session["UserId"]); else return 0; >set < HttpContext.Current.Session["UserId"] = value; >> 

First you have to store value in your session as soon as you application starts.

User user = new user(); // consider you have a User class protected void btnLogin_OnClick(object sender, EventArgs e) < _user.Username = this.txtUserName.Text; _user.Password = this.txtPassword.Text; if (_user.Validate()) < General.UserID = _user.UserID; // here you are storing the id of logged in user Response.Redirect("~/HomePage.aspx"); >else < this.labelNotice.Text = "Invalid Username or Password"; >> 

To access the value of this session on any page in javascript,

   

I imported my General class which is placed in the Models folder in MyProject solution.

Источник

Textbox value in Javascript

The following Asp.Net program shows how to get asp.Net TextBox value by using JavaScript.

The value property sets or returns the value of the value attribute of a text field. It contains the default value OR the value a user types in.

In order to set the value of textbox, we need to use:

Lets say you have a asp.net label like below

then you can get the value of the above label using javascript using the below code

  1. What is Virtual Directory
  2. What is HttpHandler
  3. Page Directives in Asp.Net
  4. What is a postback
  5. What is IsPostBack
  6. What is global.asax
  7. Difference between Machine.config and web.config
  8. Difference between HTML control and Web Server control
  9. What is Query String
  10. Difference between Authentication and Authorization
  11. How to secure Connection Strings
  12. What is ASP.Net tracing
  13. Passing values between Asp.Net pages
  14. Differentiate between client side validation and server side validation
  15. How to Get host domain from URL
  16. Adding a Favicon To Your Website
  17. AutoEventWireup attribute in ASP.NET
  18. Can I use multiple programming languages in a ASP.net Web Application?
  19. Difference: Response.Write and Response.Output.Write
  20. How many web.config files can I have in an application?
  21. What is Protected Configuration in asp.net?
  22. Static variablesin .Net , what is their life span?
  23. Difference between ASP Session and ASP.NET Session?
  24. What does mean Stateless in Asp.Net?
  25. What is the Difference between session and caching?
  26. What are different types of caching using cache object of ASP.NET?
  27. Which method is used to remove the cache object?
  28. How many types of Cookies are available in ASP.NET?
  29. What is Page Life Cycle in ASP.net?
  30. What is the code behind and Inline Code in Asp.Net?
  31. What is master page in ASP.NET?
  32. Can you change a Master Page dynamically at runtime?
  33. What is cross-page posting in ASP.NET?
  34. How to redirect a page in asp.net without performing a round trip ?
  35. How to register custom server control on ASP.NET page?
  36. How do you validate Input data in Asp.Net?
  37. What’s the difference between ViewData and ViewBag?
  38. Difference between Response.Redirect and Server.Transfer
  39. What is the function of the CustomValidator control?
  40. Define RequiredFieldValidator?
  41. Difference between custom control and user control
  42. Difference between Label and Literal control in ASP.Net
  43. What are the major events in Global.Asax file?
  44. What is Event Bubbling in asp.net ?
  45. What is Delay signing?
  46. What is the difference between in-proc and out-of-proc?
  47. What is the difference between POST and GET?
  48. A potentially dangerous Request.Form value was detected from the client

Источник

Getting a value from a JavaScript function to my ASP.NET / C# Code-Behind

I got a code snippet for a date and time picker i found in this place: Date and Time Picker I didn’t manage to insert it into my code normally from some reason so i just used the demo code on the bottom and pasted it in my ASP.NET site and this is the code:

// Head  // Body     

It works fine and i can see and choose a date and time in my page, but as stated in the API in order to get the time to my Code-Behind i have to use this JavaScript function:

The problem is it’s a JavaScript function which obviously returns some data, and i have no idea how to get it inside my C# code, I’ve looked everywhere and found some solutions that didn’t work out. Hope you could tell me what should i do to get it, Thanks!

Add an asp:HIddenField or plain to your page, and then deposit the value of picker.getLocalDate into that hidden field’s ID via document.getElementById(). When you postback, it will be included in the data sent back to the server.

I understood that hidden input is the answer, but i’m not really sure on how to use it together with JavaScript

2 Answers 2

add this code to java script :

document.getElementsByName('mydate').value = picker.getLocalDate(); 

add this code between form tag :

use this code in you’r code behind :

string myDate = mydate.Value; 

but be careful use javascript after all element.

You have several approaches, you haven’t indicated your technology so I’ll cover several approaches.

The simplest approach would be the hidden or runat . To demonstrate, I’ll start with the runat approach:

// Front End: // Back End: Console.WriteLine(txtDate.Value); 

So in this instance, if your JavaScript modifies the Text Box, when your server side code runs it will call the value on the field.

This approach is similar to the HiddenField or Hidden . You store the value in a container, that is exposed to the server for easy transport from the Client to the Server.

Doesn’t matter which one you utilize, the server can access either. You simply need to have JavaScript append a value.

The other two approaches, work more ideally for a Service. When you call another page or a Controller, you in essence have a parameter. Which will indeed, allow you to transfer the data.

However, I’m not sure if those are the approaches you actually need though. After looking at the documentation, this should solve your issue:

// Front End: // Back End: var example = txtDate.Value; 

Источник

How to pass a value into a javascript function within an aspx page onClientClick

I want to check the textbox value before postback occurs. I set the onClientClick value to my function but I don’t know how to pass the data to check, in this case I want to check the txt1 entered text.

function check(txt) < var pattern = /^7(,9)?$/; if (!pattern.test(txt)) < return false; >else < return true; >> 
$('#txt1').keypress(function (e) < var key = String.fromCharCode(e.which); var txt = $(this).val() + key; if (check(txt)) < // do sth >else < e.preventDefault(); // do sth >>); 

3 Answers 3

Edit:
Other methods :

  1. You can add it on server side : LinkButton1.OnClientClick=»check(document.getElementById(‘» + txt1.ClientID + «‘).value;)» ;
  2. If you want to remain in the aspx page, you have to put a name of a javascript function in the OnClientClick and implement the javascript function in a script tag :
   

IE8 does not parse the semi colon correctly. Just remove it. Furthermore it replaces for this line: getElementById(‘<%=txtPenal.ClientID%>’). Note ‘<‘ and it throws me a runtime javascript error: object not found.

OK, I have edited my post with other methods : it seems to be impossible to add directly an asp variable in a linkbutton onclientclink. Even the answer given in this post does not work for me.

You have several approaches.

function checkValue(e) < //If it has a target, use it. Otherwise, use srcElement (for IE) var ctrl = e.target || e.srcElement; //Do whatever you need to with the text, no button necessary. >; function bindEvent(ctrl, event, handler, propagates) < if (ctrl.addEventListener) < ctrl.addEventListener(event, handler, propagates); >else < ctrl.attachEvent("on" + event, handler); >>; window.onload = function () < var myCtrl = document.getElementById(''); bindEvent(myCtrl, "keydown", checkValue, false); >; 

Here, you are binding the events to the controls behind the scenes (preferable) and removing that logic from your presentation layer (your .aspx).

Both approaches will work, but I’d suggest going with option two for separation of concerns.

Источник

Оцените статью