Redirect back to Default.aspx - c#

I have a default.aspx (c#) page which has a simple Post AJAX call to a WebMethod that returns a JSON object, so that I can then populate a DataTable. All worked fine until I introduced a login page. Now, when a user is redirected to the Default page, after logging in, the Post never appears in FireBug.
This is my AJAX call:
$.ajax({
type: 'POST',
url: '/Default.aspx/GetValueDateSummary',
contentType: 'json',
data: {},
sucess: function (response) {
renderTable(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});
});
with the code behind being:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static List<ValueDateSummary> GetValueDateSummary()
{
some code in here.....
return drList;
}

sucess: function (response) {
should be
success: function (response) {

Are you using a ScriptManager object? If so, I believe that you need to enable page methods for it to work.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Ok, i sorted it.
here is the complate Ajax call, seems i was missing the proper contentType and dataType
$.ajax({
type: 'POST',
url: 'Default.aspx/GetValueDateSummary',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
console.log(response);
alert(response.d);
renderTable(response.d);
},
error: function (errMsg) {
$('#errorMessage').text(errMsg);
}
});

Related

Ajax method always goes to error function

I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live

What is wrong with this JQuery AJAX code

I was facing some problem with AJAX code. I was using MVC3 for our project. My requirement is bind the dropdown value using AJAX when page load. What happens when loading the page, the AJAX request send to the controller properly and return back to the AJAX function and binds the exact values in dropdown. But sometimes (When page refreshed or first time load) its not binding retrieved value. Rather its showing default value. Pls see my code and suggest me where i am doing wrong.
Edit: Even i tried to use async property to false. Its not at all send to the controller action method for getting the data.
Code
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetUser", "Invoices")',
data: "{'id':" + JSON.stringify(currval) + "}",
dataType: "json",
async: true,
success: function (data) {
$("#User-" + curr).select2("data", { id: data.Value, Name: data.Text });
$(this).val(data.Value);
}
});
Thanks,
Let's say your Action method is below
public JsonResult hello(int id)
{
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
and JQuery should be like below
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var currval = 2;
$.ajax({
url: 'URl',
async: true,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ id: currval }),
success: function (data) {
}
});
});
</script>
You are declaring your data property incorrectly. Try this:
data: { id: currval },

Unknown web method parameter method name

I'm building a Web Application in which I'm trying to call a WebMethod in a WebForm, I've tried every single page in google but I'm still getting nothing. This is an example of the Jquery Ajax Call
$.ajax({
type: "Post",
url: "Default.aspx/Return",
data: {dato:'Hello'},
contentType: "application/json; chartset:utf-8",
dataType: "json",
success:
function (result) {
if (result.d) {
alert(result.d);
}
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
And this is the WebMethod in the codebehind
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public static string Return(string dato)
{
return dato;
}
You can't access a Static method this way. Remove the "Static" reference and it will work. Also, like someone else said - do not use that as your method name "Return".
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string Return(string dato)
{
return dato;
}
I think, on your success event the function with result is used, which is a string and u are trying to access property named d assuming result is an object.
use of only alert(result);
User F12 tool to debug and find your error.
Make sure that you have enabled page methods in your ScriptManager element:
<asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />
and your method
$.ajax({
type: "Post",
url: '<%= ResolveUrl("~/Default.aspx/Return") %>',
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});
Try this
var url = window.location.pathname + "/Return";
$.ajax({
type: "Post",
url: url,
data: {dato:'Hello'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (result) {
alert(result.d);
},
error:
function (XmlHttpError, error, description) {
$("#grdEmpleados").html(XmlHttpError.responseText);
},
async: true
});`

Why is this AJAX call returning the entire page contents?

I am trying to call the following webmethod found in one of my aspx page files:
[WebMethod]
public static string GetReportDetails()
{
var reportDetails = DataAccess.Database().GetBusinessInterestReportDetails(HttpContext.Current.User.Identity.Name);
var json = BusinessInterestReport.GetJson(reportDetails);
return json;
}
And this is the javascript that i'm using to call the webmethod:
$.ajax({
type: 'POST',
url: 'SummaryReport.aspx/GetReportDetails',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
The javascript that makes this ajax call:
$('.reportOption').click(function (e) {
$.ajax({
type: 'POST',
url: 'SummaryReport.aspx/GetReportDetails',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
})
The ScriptModule config is already in the web.config. The break point is not even getting hit on the webmethod and the entire page's content is returned. Any idea what's causing this?
EDIT:
Using Chrome's debug console I found this error:
[ArgumentException: Unknown web method GetReportDetails.
Parameter name: methodName]
System.Web.Script.Services.WebServiceData.GetMethodData(String methodName) +516665
System.Web.Handlers.ScriptModule.OnPostAcquireRequestState(Object sender, EventArgs eventArgs) +168
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Why would it not pick up the method name? I've also enabled PageMethods using <asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
P.S. Just realized that i'm calling it from within an iFrame. Could this have anything to do with the issue?
I think you need to explicitly add contentType, as its default value is application/x-www-form-urlencoded; charset=UTF-8, which is not you are after.
So you might want to revise your jQuery code a bit.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SummaryReport.aspx/GetReportDetails",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
Remove the static keyword from your GetReportDetails method.
Don't write plumbing code (JSON serialization/deserialization) in your web method. Simply take/return models (.NET POCO objects):
[WebMethod]
public static string GetReportDetails()
{
var reportDetails = DataAccess.Database().GetBusinessInterestReportDetails(HttpContext.Current.User.Identity.Name);
return reportDetails;
}
and then consume:
$.ajax({
type: 'POST',
url: 'SummaryReport.aspx/GetReportDetails',
contentType: 'application/json',
success: function (data) {
// the actual object will be inside data.d
var reportDetails = data.d;
// Now you could directly use the properties of your model
// For example if your ReportDetails .NET type had a string property
// called FooBar you could directly alert(reportDetails.FooBar);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('An error has occured: ' + errorThrown);
}
});
Things to notice:
We have explicitly specified the contentType: 'application/json' to indicate to the web method that we want to use JSON as transport mechanism
We have gotten rid of the dataType: 'json' property because jQuery is intelligent enough to use the Content-Type response header and automatically parse the data parameter that is passed to your success callback.
I would also recommend you reading this article about consuming ASP.NET PageMethods directly from jQuery.
Fixed it. It turns out that the inherits attribute was missing at the top of the aspx file.
So now I have:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SummaryReport.aspx.cs" MasterPageFile="~/MasterPages/SummaryReports.Master"
Inherits="Web.SummaryReport"
%>
An addition I would like to contribute here from my experience in this problem.
if you are using a content page or master page, you can't call the WebMethod by accessing the page ,instead add a webserivce page and use it, please refer to this link it worked with me.
http://forums.asp.net/post/5822511.aspx
I copied it here
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function MyFunction() As String
Return "Hello World"
End Function
Then you can call the webmethod from master page or content page like following:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function MyFunction() {
var request = $.ajax({
type: 'POST',
url: 'HelloWord.asmx/MyFunction',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (serverdata) {
alert("Done " + serverdata);
},
error: function (error) {
alert("error ");
}
});
return false;
}
</script>
please be sure to uncomment the line :
System.Web.Script.Services.ScriptService
in the webservice page since when creating the page it will be commented

Data Format Jquery Ajax Post Cross Domain Call Asp.Net MVC method

I am trying $.ajax post MVC call from http to https cross domain.
Client Side
enter code here
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: '{name:"John"}',
dataType: "json",
success: function (data) { pdata = data; }
});
Server Side
[RequireHttps]
[HttpPost]
public string VerifyEmail(string name){
return "got it"
}
I have added Access-Control-Allow-Origin to web.config so the call can be established fine. Now the problem is on server side I got variable name = null
I have also checked debugging and found the data has actually been send to server
HttpContext.Request.Form
{%7bname%3a%22hello%22%7d}
[System.Web.HttpValueCollection]: {%7bname%3a%22hello%22%7d}
The question is how I could retrieve it from the web method?
%7bname%3a%22hello%22%7d This is HTML entity String please Decode the String then parse for JSON.
I think you can change your call to
$.ajax({
type: 'post',
crossDomain: true,
url: 'https://localhost/views/Member/VerifyEmail',
beforeSend: function () { alert('I am sending'); },
data: 'John',
dataType: "text",
success: function (data) { pdata = data; }
});

Categories

Resources