I'm stuck, who can help me out? In my LogOn.aspx View I've login controls (Username, Password, RememberMe) inside a FORM tag:
<form id="loginform" method="post" action="/Account/LogOn/">
Below that, I've a hidden DIV with a OPTION dropdownlist and a confirm-button, with a onclick_event:
$.ajaxSetup({ cache: false });
$.ajax({
type: "GET",
url: "/Account/SetCompanyAndContinue",
data: "{ 'id' : '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
First, the user logs in. In jQuery, I post the login credentials via AJAX:
var loginCred = new Object();
loginCred.Username = $('#userName').val();
loginCred.Password = $('#password').val();
loginCred.RememberMe = $('#rememberMe').checked;
var myJsonObject = JSON.stringify(loginCred);
$.ajaxSetup({ cache: false });
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Account/LogOnAjax/",
data: myJsonObject,
dataType: "json",
success: function(data) {
PostCredentialsSuccess(data);
}
});
This POST works perfect. The breakpoint at the Controller Action is hit by the debugger and returns a JSON object of data. I put this JSON data into the OPTION dropdownlist. This Option Dropdownlist is then presented to the user. Then, when the user clicks the confirm-button, a second AJAX call is made:
$.ajaxSetup({ cache: false });
$.ajax({
type: "GET",
url: "/Account/SetCompanyAndContinue",
data: "{ 'id' : '1'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
I would expect that the Controller Action named "SetCompanyAndContinue" gets hit:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult SetCompanyAndContinue(string id)
{
SessionAdapter.CustomerID = Convert.ToInt32(id);
return null;
}
But it ain't happening, instead, the default Controller Action get's hit the first time:
public ActionResult LogOn()
{
return View();
}
BUT(!) the second time I click (the same) confirm-button the Controller Action finally hits [SetCompanyAndContinue].
Can somebody tell me what I'm doing wrong? Many thanks in advance.
you need to pass the data property as a javascript object not as a string
$.ajax({ type: "GET",
url: "/Account/SetCompanyAndContinue",
data: ({id : 1}),
contentType: "application/json; charset=utf-8",
dataType: "json" });
i recommend to use firebug to look at the actual HTTP Request that do get send from jQuery, that way tiny mistakes like this get obvious very quickly.
hth
try using a link to submit instead of a normal submit button, it probably has a conflict somewhere between the click, ajax and form.
I didn't know whether I got the correct information. But as per your description any click on the "submit" button will try to do the "Post" method and not the "Get" method.
The "Get" call is done only when you visit the page at first or refresh the url.
Use the link button to do the "Get" action.
That's why in your sample its calling "/Account/LogOnAjax/" this action with "Post" method.
To compare the different GET requests you can use a debugging HTTP proxy like Fiddler or Charles.
marc.d was right
A general rule of thumb (at least it works for me): if your action isn't being hit like you expect, it's likely something is wrong with your route params or if you're falling through to the default route, the form data being sent with the post isn't what's expected. I was using $(this).serialize() as a JQuery data arg for a $post and one of my hidden form fields was empty. The action, which wasn't included in any route, (I was letting it fall through to the default in this case), never saw the post.
Stupid mistake from my behalf:
i've added a cookie to the response-stream which made the webbrower behave unpredictable.
i've forgot to mark this one as answered
Related
I have passed the Model object from the View to controller action method through the AJAX post call. Inside the action method, we have a some business logic to be perform based on the received input fields. if business logic fails, then we will return the error message to user else, then we need to redirect the user to some other page. in this case, Redirection to other page is not working in the AJAX post call.
Could you please provide me the any alternative approach on this?
Note:- i need to perform this post operation in the AJAX call.
Thanks
You can simply check if the status is an error and if so redirect in your ajax call
$.ajax({
url: '/ThingToDo/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: data,
success: function (status) {
if (!status.error) { alert(!status.error); }
else { window.location.href = "/Redirecthere/"; }
}
Current Scenario
I am using MVC 4, .net 4.5 on vs2012. I have an action which accepts a custom type. This custom type(model) is tightly bound to a view. I am making a POST via AJAX using JSON. Post will only post the relevant data and no form. Its content type is "application/json; charset=UTF-8". I am getting a nicely populated(read valid) model in my action.
The issue
Now I need to add a custom filter but I am unable to access the data via Request, Request.Form, Request.Param? I have been looking in System.Web.HttpContext.Current. If data is getting populated in my model, then it has to be somewhere in the request itself. I guess I am missing the finer print.
The javascript for posting data is somewhat like
$("#postData").click(function (event) {
var savedObject = getJson(savedObject, parentContext);
$.ajax({
url: '/controller/action',
contentType: 'application/json',
dataType: 'json',
data: savedObject,
type: "POST",
success: successCallBack,
error: errorCallBack
});
});
I see your stated wish of sending JSON data only. If you really need to stick to this, you can access the raw parameters via Request.InputStream.
Controller:
var input = new StreamReader(Request.InputStream).ReadToEnd();
This will get you a URL encoded string that you can manually parse.
Really, I would recommend Shahrooz's answer as the correct way to get where you want to go.
If the controller's Request.Form is not populating for your Ajax post, it is likely because you are manually serializing and sending the data to the controller with a contentType of application/json (a common scenario).
Here is an jQuery.ajax example that will NOT populate Request.Form on the controller.
// JSON serialized form data.
var data = {"id" : "1234", "name" : "Dave"};
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data || {}),
success: function () { }
});
Changing the contentType will cause the controller to process the post like a form submission.
// Form encoded data.
var data = {"id" : "1234", "name" : "Dave"};
data = $.param(data);
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "json",
data: data,
success: function () { }
});
You can also leave contentType undefined as application/x-www-form-urlencoded; charset=UTF-8 it is the jQuery default.
I would note that I only used $.ajax to better illustrate what is going on. You could also use $.post, though you will still need to send form encoded data
I dont know what is your code but .If you remove contentType: "application/json; charset=utf-8" from your call to jQuery.ajax the default content type (form-urlencoded) will be used and the json data you have specified as your data parameter (data: { i: i, s: s, b: b }) will be mapped correctly to your action parameters....so unless you really want to send json data just remove the contentType and you will be fine.....look at this
I have been successfully using the AntiForgery option with Ajax in Orchard Modules for a while. Recently, I have been wanting to change from using the default ContentType = 'application/x-www-form-urlencoded; charset=UTF-8' to a JSON payload (ContentType='application/JSON').
As soon as I do this I get an exception thrown by ASP.NET 'A required anti-forgery token was not supplied or was invalid.'. OK, but how do I go about adding the __RequestVerificationToken while preserving JSON payload?
For reference, here is the code I'm using:
var config = {
url: url,
type: "POST",
data: data ,
dataType: "json",
contentType: "application/json; charset=utf-8"
};
$.ajax(config);
Controller (blows up with 'A required anti-forgery token was not supplied or was invalid.' before it gets here):
[HttpPost]
public ActionResult Update(ShoppingCartItemVM[] items)
{
// do stuff
}
Is this a limitation of the Orchard AntiForgery wrapper or of the MVC AntiForgery functionality? Or am I being stupid (again)?
Giscard is correct. I'll dig a bit deeper.
Note: Only the "post" results in orchard controller require the anti forgery token. So there is less of a requirement to remember that where using a "Get" in a request for json.
Often you will want to send more data than just the request token. In that case the 'data' object you send with your request must contain that __RequestVerificationToken value. In that case jQuery is useful for example:
var defaultPostValues = { __RequestVerificationToken:'#Html.AntiForgeryTokenValueOrchard()', id: 1, ..etc.. };
var myValues = { answers: [1,5,5,10] };
var data = $.extend({}, defaultPostValues, myValues);
var config = {
url: url,
type: "POST",
data: data ,
dataType: "json",
contentType: "application/json; charset=utf-8"
};
$.ajax(config);
The anti-forgery token can also be turned off per module definition (if I remember correctly?).
Module.txt
Name: Polls
AntiForgery: false
Author: Matt
... removed for brevity
Features:
Polls
... etc
However I would recommend using the antiforgery if your calls are within Orchard's modules, and disabling if and only if your data is needed else where by external requests. But I would recommend WebAPI within Orchard for that case but that creates a whole new story and probably likely moves far out of scope.
Maybe try this:
​data = {color: 'red', weight:'20lbs'};
// do some more work...
// Append the anti-forgery token to the POST values:
data['__RequestVerificationToken'] = '#Html.AntiForgeryTokenValueOrchard()';
// Make the .ajax() call:
var config = {
url: url,
type: "POST",
data: data ,
dataType: "json",
contentType: "application/json; charset=utf-8"
};
$.ajax(config);
If you are forming the json somewhere other than a razor view, you can do the #Html.AntiForgeryTokenValueOrchard() inside a razor view and pass it to a javascript object or variable so you can add it to the json via javascript.
EDIT: In addition to the method Matthew posted, you can also append the anti-forgery token to the POST values right before you make the AJAX call without using .extend(). Example: http://jsfiddle.net/JC66L/.
This is my code for the .ajax() call:
$.ajax({
type: "POST",
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
}
In addition to using type:"POST" as above, I also tried using $.ajaxSetup({type: "post"}); above this code block.
In both cases, the values in the data key are being appended to the URL. I want a clean URL with no parameters. This code is actually a part of an autocomplete field, it's wrapped into an anonymous function and given a key source like the main jQueryUI examples.
Note The actual URL is immaterial, I don't know if geonames supports POST requests but that's going to change later, this is just an example.
Simply add your parameters like this :
url: "http://ws.geonames.org/searchJSON/" + param,
If you want to force POST, you can try jQuery.post()
It is not possible to make a POST request with the JSONP datatype.
JSONP works by creating a <script> tag that executes Javascript from a different domain, it is not possible to send a POST request using a <script> tag.
If you specify dataType: "jsonp" and type: "POST", the "jsonp" takes precedent and it gets sent as a "GET" request (the "POST" gets ignored).
Would anybody know why my parameter is being "converted" to lowercase when it hits my ASP.NET MVC controller action?
I can only assume it is being converted as looking at data value just prior to the ajax request it is in correct casing, but then when debugging my action method within .NET during the ajax request and checking the incoming parameter, it has been converted to lowercase?
This is causing dramas for me as I need to keep the case entered by the user.
Code below, example data being sent is: 'SimpleDATATest1'
$.ajax({
type: "GET",
url: "/configuration/module-message-types/GetTranslation",
data: "messageToTranslate=" + messageToTranslate,
dataType: "json",
success: function(result) {
// Insert the returned HTML into the <div>.
$('#TranslationResponse').html(result.message).fadeIn('fast');
$("#" + ajaxLoadImgId).hide();
},
error: function(req, status, error) {
$('#TranslationResponse').text('Could not load example translation message, please try reloading the page.');
$("#" + ajaxLoadImgId).hide();
}
});
And MVC Action method signature is:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetTranslation(string messageToTranslate)
However, when checking the value of 'messageToTranslate' it is returning as: 'simpledatatest1'.
How can I stop whatever forces at work from changing this?
Nevermind... I found this that I implemented was the culprit:
http://www.coderjournal.com/2008/03/force-mvc-route-url-lowercase/