jQuery Validate with WebForms & WebService - asp.net

Right now I have simple form with a single input. I'm trying to use the remote part of jQuery Validate to call my webservice that right now is just returning false. The problem I'm having right now is when it calls my webservice it is pulling the name of the input which is some garbage created by .net. Is there a way to override this and use the Id of the input verse the name of the input. Here is my jQuery:
$(function () {
$('form').validate();
$("#tbSiteName").rules("add", {
required: true,
remote: "webservices/webservice.asmx/HelloWorld"
});
});
Here is my HTML:
<label for="tbSiteName">Name:</label>
<input name="ctl00$MainContent$tbSiteName" type="text" id="tbSiteName" class="required" />
Here is the header info from Chrome: (notice the Query string params)
Accept:application/json, text/javascript, */*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Type:application/x-www-form-urlencoded
Cookie:ASP.NET_SessionId=qvupxcrg0yukekkni323dapj
Host:localhost:56803
Referer:http://localhost:56803/Default.aspx
User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10
X-Requested-With:XMLHttpRequest
Query String Parameters
ctl00%24MainContent%24tbSiteName:ts
From the server side I'm getting a 500 Internal server error because my signature doesn't match my post.
Webservice Code:
[WebMethod]
[ScriptMethod]
public bool HelloWorld(string tbSiteName) {
return tbSiteName.Length > 5;
}
Thanks for the help.

Unfortunately, to my knowledge, there's no way to get around this when using ASP.Net WebForms server controls such as <asp:textbox>. Although in .NET 4 you have the ClientIdMode="Static" attribute (see here) to disable the auto-generated client IDs, that does not affect the name attribute.
Rick Strahl has suggested in response to comments on his blog post that if you really need predictable names, you should just use an html <input> control:
ClientIDMode only affects the ID not the NAME attribute on the control, so for post back form elements the name will still be a long name as held in UniqueID. This is reasonable though IMHO. If you really need simple names use plain INPUT elements rather than ASP.NET controls especially if you don't rely on POSTBACK assignment of controls anyway to retrieve the values by using Request.Form[].
Have you considered just using a client-side <input> instead of an <asp:textbox runat="server">?
Additionally, have you considered dropping ASP.NET WebForms and using MVC? ;-)

This is the answer I've came up with. I had to change my asp:textbox to a HTML input in order to get this to work. Also, I had to change the web.config to all HttpGet to my webservice. This is painful at best. I've also lost viewstate on the control by using a standard input. I'd love to switch this over to MVC, but it is just not an option.
Thanks for the help.
$("#tbSiteName").rules("add", {
required: true,
remote: function() {
var r = {
url: "/webservices/ipmws.asmx/SiteValid",
type: "POST",
data: "{'tbSiteName': '" + $('#tbSiteName').val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return (JSON.parse(data)).d; }
}
return r
},
});

Related

Where do ajax headers go when making a server call?

I am new to the web developer side and am trying to make sense of how AJAX headers work. We use .NET Framework MVC project with some methods on the controller that are called by our views to get some data.
Example of our view ajax call to the server:
jQuery.ajax({
type: "POST",
data: { "ElementPath": ElementPath },
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
url: "" + BasePath + "/Home/GetAttributes",
});
The GetAttributes method on the server accepts a string as a parameter and returns a string of JSON objects. When I put a breakpoint on the method, the only thing I see in the string parameter is the contents of ElementPath, and nothing to do with headers. In my mind the server method would also have the contents of forgeryId. So what exactly is using the headers and how?

Persisting Session State via multiple request using jQuery $.ajax()

just been trying to recieve the session value from multiple jquery ajax requests on the same domain name. i think i understand that each request is kind of a virtual browser request so the session is mutally exclusive to each request, but there must be a way some how, has anyone solved this. Basically this is what im trying to do:
I have tries using type: GET and POST but still no luck.
Can anyone help please, Thanks?
First request - Stores the product id in a session
$.ajax({
url: 'http://localhost/websitetest/test.aspx?storeproduct=' + productid,
type: 'GET',
async: true,
success: function(data) {
}
});
Second Request - From the callback variable "data" recieves the product id from the session
$.ajax({
url: 'http://localhost/websitetest/test.aspx,
type: 'GET',
async: true,
success: function(data) {
var productID = data;
}
});
There is no question to send ajax request while accessing Session variable from asp page.
Simply you can do is :
<%
String session_var = Session("name_of_session_variable");
%>
Even if you still want to try Ajax, I think you will need to print the session variable in test.aspx file using Response.Write(), which will automatically return the content.
Please check this for further reference.
Please correct me as well if I am wrong.
Thank you.

JQuery consuming ASP.Net Web Service webserver - Request format is unrecognized for URL unexpectedly ending in

Done a lot of Googling on this but cant seem to find an answer.
When I call my web service from Jquery I am receiving the error
Request format is unrecognized for URL unexpectedly ending in '/AirportSearchGeneric'.
Factors
I am currently calling a webservice that is on the same machine but on a different webserver (calling app is port 64004 and receiving app is 1400) - possible cross "domain" issue? Both are local host.
Both are using the test web server that is part of visual studio.
I have tried adding the 2 protocols to the web.config (add name="HttpGet" add name="HttpPost")
The error occures in the Event Viewer on the server.
I get the following in Firebug...
OPTIONS AirportSearchGeneric
http://localhost:1400/services/airportservice.asmx/AirportSearchGeneric
500 Internal Server Error
localhost:1400
... not seen OPTIONS before but the request is being accessed with a POST request.
JQuery code...
$.ajax({
type: "POST",
url: "http://localhost:1400/services/airportservice.asmx/AirportSearchGeneric",
data: "{'criteria':'EGBB', 'maxResults':'10'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
Web service code...
[WebService(Namespace = "http://localhost/WebServices")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AirportService : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string AirportSearchGeneric(string criteria, int maxResults)
{
IAirportService svc = new Airports.AirportService.AirportService();
List<AirportSearchResult> res = svc.AirportSearchGeneric(criteria, maxResults);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(res.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, res);
string jsonString = Encoding.Default.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
}
... dont think its a problem in here as when debugging, no code in here gets executed.
Pretty sure I have covered off all of the reasons I have read as to why this occurs so would be greatful for any advice on how I can get this working.
Cheers.
For reference the firebug headers are as follows:
Host localhost:1400
User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729; .NET4.0E)
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-gb,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Origin http://localhost:64004
Access-Control-Request-Me... POST
(No response is received in firebug apart from the 500 error, there is no html response at all).
Using different ports on the same machine is considered cross domain and not allowed by the browser as you were suspecting.
You either call the other port by tricking the browser using JSONP (if can limit yourself to only using GET requests) or change one of the ports to be the same as the other.
Ajax Cross Domain Calls

jsonp cross domain only working in IE

EDIT: At first I thought it wasn't working cross domain at all, now I realize it only works in IE
I'm using jQuery to call a web service (ASP.NET .axmx), and trying to us jsonp so that I can call it across different sites. Right now it is working ONLY in IE, but not in Firefox, Chrome, Safari. Also, in IE, a dialog pops up warning "This page is accessing information that is not under its control..."
Any ideas?
Here is the code:
$.ajax({
type: "POST",
url: "http://test/TestService.asmx/HelloWorld?jsonp=?",
dataType: "jsonp",
success: function(data) {
alert(data.prop1);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status + " " + textStatus + " " + errorThrown);
}
});
And the server code is:
[ScriptService]
public class TestService : System.Web.Services.WebService{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void HelloWorld() {
string jsoncallback = HttpContext.Current.Request["jsonp"];
var response = string.Format("{0}({1});", jsoncallback, #"{'prop1' : '" + DateTime.Now.ToString() + "'}");
HttpContext.Current.Response.Write(response);
}
}
Glad it's working now.
You're trying to send the parameter, "jsonp" -- that you need to pass for the "padding" part of the json -- as a GET parameter, i.e. in the URL string. Which is the right thing to do.
But because you've specified POST, that's not happening. Effectively, because you're specifying POST, the server is expecting all the parameters to be in the POSTed data, not in GET variables, so it's not checking the URL to retrieve the parameter.
I think it's possible that jQuery is being quite forgiving/smart about how it's doing the JSON evaluation, and therefore still working in IE, because (a) if the server doesn't read the "jsonp" variable, I think it'll send back "({'prop1' : '<today's date>'})", which is still evaluate-able as JSON, and (b) IE doesn't have the same restrictions on cross-site scripting ("same origin" policy) as the other browsers. But I'd need to debug it to be sure.
I'd suggest using FireBug in Firefox to debug what's going on with this sort of request in the future, but the main take-away is that if you're sending parameters as part of the URL, use GET, not POST.
Cheers,
Matt
Unless you specify the jsonp and/or the jsonpCallback option, jQuery auto-generates the function name for you, and adds a query param like callback=jsonp1272468155143. Which means your application needs to output using that function name.
You can always set jsonpCallback to test, in which case your example would work.

Ajax GET requests to an ASP.NET Page Method?

A situation I ran across this week: we have a jQuery Ajax call that goes back to the server to get data
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: fullMethodPath,
data: data,
dataType: "json",
success: function(response) {
successCallback(response);
},
error: errorCallback,
complete: completeCallback
});
fullMethodPath is a link to a static method on a page (let's say /MyPage.aspx/MyMethod).
public partial class MyPage : Page
{
// snip
[WebMethod]
public static AjaxData MyMethod(string param1, int param2)
{
// return some data here
}
}
This works, no problem.
A colleague had attempted to replace this call with one where type was "GET". It broke, I had to fix it. Eventually, I went back to POST because we needed the fix quick, but it has been bugging me because semantically a GET is more "correct" in this case.
As I understand it, jQuery translates an object in data to a Query String: /MyPage.aspx/MyMethod?param1=value1&param2=value2 but all I could get back was the content of the page MyPage.aspx.
Is that just a "feature" of Page methods, or is there a way of making a GET request work?
For security reasons, ASP.Net AJAX page methods only support POST requests.
It is true that ASP.NET AJAX page methods only support POST requests for security reasons but you can override this behavior by decorating your WebMethod with this these both attribute:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
I felt that the accepted answer was incomplete without pointing out a work around.

Resources