MyMasterPage.master
<head runat="server">
<script type="text/javascript">
$(document).ready(function() {
var userName = '<%# System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString() %>';
alert(userName);
$.ajax({ type: "POST",
url: "DemoWebService.asmx/GetFulName",
contentType: "application/json; charset=utf-8",
dataType: "xml",
dataType: "json",
data: "{'networkId':'" + userName + "'}",
processData: false,
error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
success: function(xml) { ajaxFinish(xml); }
});
});
</script>
</head>
Even though the userName variable is blank, I get the logged in user from my WebMethod:
[WebMethod]
public string GetFulName(string networkId)
{
//return networkId + " Full Name";
return networkId + " From Server: " + System.Web.HttpContext.Current.Request.ServerVariables["AUTH_USER"].ToString();
}
Since I am checking on the master page, what is the best practice to store the authentication result so that I do not have to check on everypage. Prior to using jquery I was storing in Session.
Thanks
web.config
<authentication mode="Windows"/>
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
You could store the result in a cookie, and then check that cookie on subsequent pages to get the logged in user's name. You would want to make sure and delete the cookie if the user logged out or their authenticated session expired.
There is a plugin available for jQuery to support reading/writing/deleting cookies.
Related
i am going to develop a new application and i have decided to use asp.net mvc4 framework.
my project is very large and i would to make a professional work,now my problem is how to use ajax for such an application.
when i tried to think to use j query ajax i found that i'll make ajax request for each entry form and it would take more time.
<script type="text/javascript">
$(document).ready(function () {
var sURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: sURL ,
data: {
//Form data to submit to controller .....},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
You can make some service function that does ajax requests and receives url and data to send.
dataService=function(url,data)
{
return $.ajax({
type: "POST",
url: url ,
data: data
contentType: "application/json; charset=utf-8",
dataType: "json",
});
};
Your dataservice method (ajax requests) returns promise object which means you can do something like:
dataService("firstUrl","firstAjaxCallData")
.then(function(){ console.log("this happens after sucessfull ajax call")});
I have the below code in my ASPX page to get some data from a webservice. I cannot use WCF so I am using the ASMX and .Net 3.5. However, what I get back is the yellow ASP.net error page talking about setting the web.config error tag to OFF. If I call my method from code behind and response.write it to the page I get a Json string that I have viewed in JSON Viewer and it parses fine. My issue here is the URL format. What am I doing wrong here. Every example I have found uses the webservice.asmx/Method format. I have also added the protocols to my web.config
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
Page Script:
$.ajax({
type: 'GET',
contentType: "application/json; charset=utf-8",
url: 'http://myserver/mywebservice.asmx/MyMethod',
dataType: 'jsondata',
success: function (msg) {
var table = "<table><tr><th>ID</th><th>Title</th></tr>"
for (var i = 0; i <= msg.length - 1; i++) {
var row = "<tr>";
row += "<td>" + msg[i].ID + "</td>";
row += "<td>" + msg[i].Title + "</td>";
row += "</tr>";
table += row;
}
table += "</table>";
$("#myDiv").html(table);
},
complete: function () {
alert("complete");
}
});
Webservice:
<WebMethod(), ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function MyMethod() As String
'removed for shorter post
End Function
UPDATE: So using the dev tools in Chrome I have found that part of my problem was the server was returning a 403 Forbidden error. After som tweaking I have come up with a partial solution that gives me back my data with json formatting. However, that json formatted text is now wrapped in XML. :-(
I have yet been able to figure out how to get the XML out of my json. Any ideas?
You should have
contentType: "application/json; charset=utf-8",
url: 'http://myserver/mywebservice.asmx/MyMethod',
dataType: 'jsondata',
similar to:
contentType: "application/json",
url: '/folderonmyserver/mywebservice.asmx/MyMethod',
dataType: 'json',
data: "{}", // needed for .Net not to blow up sometimes - or send real data
and in your success: reference msg.d (or have a translation to isolate that for .Net) given your .net version
success: function (msg) {
var mydata = msg.d;
var table = "<table><tr><th>ID</th><th>Title</th></tr>"
for (var i = 0; i <= mydata.length - 1; i++) {
I have an ASP.Net 4.0 Web Service method that returns a well-formed XML document. I am successfully displaying the XML in a browser locally and once deployed on the production server.
When I try to call the method via jQuery ajax I'm getting the error:
XML Parsing Error: no element found Location: moz-nullprincipal:{6c0c99b3-0fed-454f-aa6e-e0fca93a521c} Line Number 1, Column 1:
$.ajax(
{
url: 'http://mywebservice.com/WebService/Service.asmx/UserData',
type: 'GET',
contentType: "text/html; charset=utf-8",
dataType: "xml",
data: 'authorizedId=1234&authorizedUser=Test&authorizedCode=xyz',
'success': function (data) {
$('#XMLContent').html(data.responseText);
},
'error': function (xhr, status) {
alert(status);
},
'complete': function (xhr) {
}
});
I've tried changing the contentType but same results.
However, I can make the call in C# like this and I get my well-formed XML:
XmlDocument document = new XmlDocument();
document.Load("http://mywebservice.com/WebService/Service.asmx/UserData?authorizedId=1234&authorizedUser=Test&authorizedCode=xyz");
ViewData["XMLData"] = document.OuterXml;
In my web service web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
Thanks...
If the web service is not on the same domain as the page, you can not use AJAX calls to fetch data from other domains.
You can create a proxy web service in your aplication which calls your external web service, then call your own proxy from AJAX/jQuery.
http://forum.jquery.com/topic/jquery-ajax-and-xml-issues-no-element-found
Hope that helps
Thanks bgs264...
Now in my aspx page:
$.ajax(
{
url: '/Home/WebService',
type: 'GET',
contentType: "text/html",
dataType: "html",
data: 'authorizedId=1234&authorizedUser=Test&authorizedCode=xyz',
'success': function (data) {
alert(data);
$('#XMLContent').html(data);
},
'error': function (xhr, status) {
alert(status);
},
'complete': function (xhr) {
}
});
In my MVC controller:
public ActionResult WebService(string authorizedId, string authorizedUser, string authorizedCode)
{
XmlDocument document = new XmlDocument();
document.Load("http://mywebservice.com/WebService/Service.asmx/UserData?authorizedId=" + authorizedId + "&authorizedUser=" + authorizedUser + "&authorizedCode=" + authorizedCode);
ViewData["XMLData"] = document.OuterXml;
return PartialView();
}
I'm implementing IHttpHandler and IRequiresSessionState and I'm using context.Session but after I set up a value in Session, it's lost in the next request. What can I do to persist the values ?
$.ajax({
url: "/test.test",
type: "POST",
data: "{'type':'GetStep'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {...}
});
The second call is similar to this, but the values that get set when I call this function are also lost on the next request.
public void ProcessRequest (HttpContext context)
{
context.Session ["Game"] = new Game (); // next time it is null
}
How do I persist values in Session state in ASP.NET ?
Do you have session state defined in your web.config? Something like this
<sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20"/>
I'm trying to call a server side method from client side via jQuery. My code is as follows:
Server side:
using System.Web.Services;
[WebMethod()]
//[ScriptMethod()]
public static void SendMessage(string subject, string message, string messageId, string pupilId)
{
//Send message
}
Client side:
$("#btnSendMessage").live("click", function(){
var subject = $("#tbSubject").val();
var message = $("#tbMessage").val();
var messageId = $("#hdnMessageId").val();
var pupilId = $("#hdnPupilId").val();
$.ajax({
type: "POST",
url: "./MessagePopup.aspx/SendMessage",
data: ("subject=" + subject + "&message=" + message + "&messageId=" + messageId + "&pupilId=" + pupilId),
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(textStatus);
},
success: function(result){
alert("success");
}
});
return false;
});
I've added a break point on the server side SendMessage method, but it's never hitting it, but when I run the code the jQuery success method is called. What could be causing this?`
To call ASP.NET AJAX "ScriptServices" and page methods, you need to use the full $.ajax() syntax:
$.ajax({
type: "POST",
url: "MessagePopup.aspx/SendMessage",
data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
See this post for details on why that's necessary: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Edit: The extension doesn't change to .asmx but remains .aspx.
It looks like you're trying to make use of a page method.
Take a look here Page Methods in ASP.NET Ajax for help
You should use web service instead of regular aspx web page. Web pages has no support to call web methods, I believe your jQuery request loads the HTML page instead. I suggest you two things:
Use Fiddler2 (with IE) or HttpFox (with Firefox) to debug AJAX requests and responses on client side.
Use WCF web service on the server side. in this case you can use SvcConfigEditor and SvcTraceViewer to configure and debug web methods on the server side.
$.ajax({
type: "POST",
url: "MessagePopup.aspx/SendMessage",
data: "{subject:'" + subject + "',message:'" + message + ",messageId:'" + messageId + "',pupilId:'" + pupilId +"'}",
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {},
error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); }
});
If this doesn't work...and gives "Syntax Error: syntax error"...then add this
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
between </compilation> and </system.web> in your Web.Config file.
Hope this will help somebody because took me a while to figure that beside jquery function i have to add that in Web.Config.
Here is code that might work in your situation.
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the button.
$("#btnSubmit").click(function () {
//get the string from the textbox
$.ajax({
type: "POST",
url: "testSearch.aspx/GetMyShippingDate",
contentType: "application/json; charset=utf-8",
data: "{'tracking_num': '" + $("#txtTrackingNumber").val() + "'}",
dataType: "json",
success: function (date) {
// Replace the div's content with the page method's return.
Success(date);
},
error: Failed
});
});
});
function Success(result) {
$("#ParcelShippingDate").html(result.d);
}
function Failed(result) {
alert(result.status + " " + result.statusText);
}
There is an example that has always work for me.
Here is the complete article http://www.webdeveloperpost.com/Articles/How-to-use-jquery-ajax-in-asp-dot-net-web-page.aspx
It works well for those that want a straight forward way of using the jquery asp.net method call back