1

I want to take a .Net server variable and user that in the data of an Ajax call.

$.ajax({
  url: "get_user_info.aspx",
  data: "user_id=<%=UserID%>" 
});

However, I get an Object Expected error with the above.

The UserID is an int in the C# codebehind.

I have tried casting it to string like this:

var useridstring = <%=UserID%>;
var mynewstring = useridstring.toString();

 $.ajax({
      url: "get_user_info.aspx",
      data: {user_id:mynewstring} 
    });

It is not working though. I've read posts here about using a hidden input with a variable, but I am hoping to avoid that method if something like the above can work.

1
  • 1
    In the second case: 1. what is the value of useridstring and, 2. in what way is it "not working"? Commented Feb 16, 2012 at 15:56

2 Answers 2

3

Your field name (user_id) needs to be a string:

var useridstring = '<%=UserID%>';


 $.ajax({
      url: "get_user_info.aspx",
      data: {'user_id':useridstring} 
    });
Sign up to request clarification or add additional context in comments.

4 Comments

Technically, the field name doesn't have to be a string, unless you're doing something odd with it (like passing an array). But your code DOES fix the problem, because of the first line - without the quotes around <%=UserID%>, javascript will try to evaluate whatever the UserID is as a variable, instead of a string.
Hmm... Still not working. I still get a Javascript error Object Expected any time I put in <%=UserID%> anywhere. If I take it out, it works fine. I put it in and the JS further down the page freaks out. I am using .Net 2.0 framework with ViewState. Could there be a conflict anywhere in there?
Can you please post your HTML (not your .net source): jsfiddle.net
So I ended up having to do the hidden field workaround. Thanks for the help.
0

I would place the variable inside a hidden div and get from jquery the inner text of this div.

var useridstring = $get('myDiv');

<div id='myDiv' style="display:none;><%:UserID%></div>

1 Comment

yes, Diodeus gave the correct answer, actually my solution do not help solving the issue...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.