I'm trying to use jquery.Ajax to post data to an ASP.NET MVC2 action method that returns a JsonResult. Everything works great except when the response gets back to the browser it is treated as a file download instead of being passed into the success handler. Here's my code:
Javascript:
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
});
return false;
});
</script>
Action method on controller:
public JsonResult CreateEnvelope(string envelopeTitle, string envelopeDescription)
{
//create an envelope object and return
return Json(envelope);
}
If I open the downloaded file the json is exactly what I'm looking for and the mime type is shown as application/json. What am I missing to make the jquery.ajax call receive the json returned?
You are missing a "return false" in the handler of your submit event. If you don't return false, then JQuery will still pass the submit as it would do normally.
<script type="text/javascript">
$(document).ready(function () {
$("form[action$='CreateEnvelope']").submit(function () {
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (envelopeData) {
alert("test");
}
});
// IMPORTANT: return false to make sure the normal post doesn't happen!
return false;
});
return false;
});
</script>
You were almost there!
I have just started using ajax similar to this and first impressions looking at your code would indicate that you dont need to call submit on the form? You only need to do the ajax call. I may be wrong but it might be that the ajax is returning the data and the page is doing a refresh where the page data is replaced with the json data?
Related
I want to incorporate jquery autocomplete widget to my aspx page. The "source" for the autocomplete comes from a webservice method.
My script looks like this:
$(".paisProc").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
url: "/ManifestService.asmx/GetPaises",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'term': request.term }),
success: function (data) {
console.log("reading results...");
response($.map(data, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));
},
error: function (err, status, error) {
console.log(status);
console.log(error);
}
});
With this setup, as users type in the input control, the expected values are returned from the webservice but the autocomplete does not seem to work. Inspecting the page with Firebug i see the ajax call to the service returns data with this format:
{"d":[{"__type":"dhl.domain.Pais","PaisId":1,"CodigoDHL":"AR","CodigoAduana":"528","Descripcion":"ARGENTINA"},
{"__type":"dhl.domain.Pais","PaisId":481,"CodigoDHL":"DZ","CodigoAduana":"208","Descripcion":"ARGELIA"}]}
I cannot see what the problem with my code, I have followed the indications from the many questions with the same issue in this site with no success yet.
If it can help, the line console.log(item.CodigoAduana) from success callback write "undefined" to the console.
.Net web services returning JSON do so by embedding the payload into a "d" property (as you can see in your capture of the JSON).
Try changing your processing of the response to read from data.d instead of just data, to get to the array you want to map, like this:
response($.map(data.d, function (item) {
console.log(item.CodigoAduana);
return {
label: item.Descripcion,
value: item.CodigoAduana
};
}));
I have a very simple page and a [WebMethod] inside it which returns a simple message. I would like to show this message through $.ajax on client side. however my website is using rewrites rules so my url becomes readable to user.
EX:
Actual webpage: www.mysite.com/about // which has about folder and a user control inside it
there is no aspx page for this instead i am using a method which gets a webpage data which is actual html page and show the content on user control.
here is Jquery part.
$(document).ready(function () {
$('.info a').click(function () {
$.ajax({
type: 'POST',
url: '/about/showServer', //which url to put here
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("result.d");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
});
});
});
C#
[WebMethod] // this method is in the user control
public static string showServer()
{
return "Hello from server";
}
How to call this method from client using $.ajax
appreciate your time and help.
EDITS
I have this structure for my website
mysite.com/about
/about/defualt.aspx --> which loads the user controls
user controls resides in
mysite.com/ConLib/Custom/about.ascx/showServer
So i set it to like this
url: '/ConLib/Custom/about.ascx/showServer',
BUT i see error in chrome developer tool in XHR request "404 error" because when you type mysite.com/conlib/blah blah ..reqrites does not allows this and throws 404 error..
Your ajax success method should be this:
alert(result.d);
Instead of this:
success: function (result) {
alert("result.d");
}
and url should be:
url: "Default.ascx/showServer", // UserControlPage/MethodName
you need to decorate your web method
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
public static string showServer()
{
return "Hello from server";
}
If your WebMethod is inside a User Control, then it needs to be moved to the ASPX page. See this post:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
The url: param should be in the form of '/MyPage.aspx/showServer'
I currently have a JSON object on my page which gets built up as users add items to it. This is all done in JavaScript/jQuery.
When the user is done adding items, I want to POST this object to a controller action and have the action return a strongly typed view using this data.
Currently, I have the jQuery.ajax POST sending this JSON object to an Action Method which then binds this object to my strongly typed Model. Problem is, I actually want this jQuery.ajax POST to redirect as if the JSON object were in a FORM and simply being submitted.
I also can't use the jQuery.post() method, which would redirect as required, as I need to be able to set the contentType to "application/json" so my binding works correctly. Unfortunately, the jQuery.post() method doesn't allow you to set this parameter.
I've read that the jQuery.post() method basically uses the jQuery.ajax() method, so I've been battling to get the jQuery.ajax() method to redirect.
I've also read that I can set the default contentType for all jQuery.ajax() methods which would then allow me to use the jQuery.post() method but want to try avoid this if possible.
Thanks
Edit: Updated with Saedeas suggestion:
My JavaScript on the 'Index' View:
<script language="javascript" type="text/javascript">
// Initialize the Shopping Cart object
var m_ShoppingCart = {
UserId: 10,
DeliveryInstructions: "Leave at front desk",
CartItems: []
};
$(document).ready(function () {
$.extend({
postJSON: function (url, data, callback) {
return $.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
});
function PostDataWithRedirect() {
var url = '#Url.Action("ConfirmOrder", "Store")';
$.postJSON(url, m_ShoppingCart, function () { });
}
function AddToCart(id, itemName, price, quantity) {
// Add the item to the shopping cart object
m_ShoppingCart.CartItems.push({
"Id": id,
"ItemName": itemName,
"Price": price.toFixed(2), // Issue here if you don't specify the decimal place
"Quantity": quantity
});
// Render the shopping cart object
RenderShoppingCart();
}
function RenderShoppingCart() {
$("#CartItemList").html("");
var totalAmount = 0;
$.each(m_ShoppingCart.CartItems, function (index, cartItem) {
var itemTotal = Number(cartItem.Price) * Number(cartItem.Quantity);
totalAmount += itemTotal;
$("#CartItemList").append("<li>" + cartItem.ItemName + " - $" + itemTotal.toFixed(2) + "</li>");
});
$("#TotalAmount").html("$" + totalAmount.toFixed(2));
}
</script>
And then the Controller Action 'ConfirmOrder'
[HttpPost]
public ActionResult ConfirmOrder(ShoppingCartModel model)
{
return View(model);
}
So when the PostDataWithRedirect() JavaScript method is called it must hit the ConfirmOrder Controller Action and be redirected to the ConfirmOrder View. The Shopping Cart object on my Index view is built up entirely in JavaScript and the user then clicks a 'Proceed to Checkout' button and is redirected etc.
PS: My full working example can be found in an the article [ How to POST a JSON object in MVC ], I just need to update this code so that it can do the post and redirect as explained above
In the success method, do a location.href = "TARGET LOCATION" to cause the page to go to TARGET LOCATION.
$.ajax({
url: myurl,data,
data: myData,
// processData: false, // you may need this option depending on service setup
success: function(){
location.href = "TARGET LOCATION";
},
type: "POST",
contentType: "application/json"
});
Return a view that redirects:
controller
return View("redirectionView");
view
RedirectionView.cshtml
#{
Layout = null;
}
<script type="text/javascript">
alert("Success! Redirecting...");
window.location = "./";
</script>
EDIT
To accommodate data retention use tempdata.
controller
TempData["collectedUserData"] = collectedData;
return View("redirectionView");
RedirectionView.cshtml
#{
Layout = null;
}
<script type="text/javascript">
alert("Success! Redirecting...");
window.location = "./Rebuilder/ActionMethod";
</script>
Controller Rebuilder
public ActionResult ActionMethod()
{
if( TempData.ContainsKey("collectedUserData") )
{
var collectedData = TempData["collectedUserData"];
}
//todo: use else clause to catch data not present
use collectedData to build new view
return View();
}
Maybe I'm not following the question, but why does the classic post, redirect, get pattern not work?
[HttpGet]
public ActionResult WhateverActionName()
{
YourViewModel yvm = new YourViewModel();
//Initalize viewmodel here
Return view(yvm);
}
[HttpPost]
public ActionResult WhateverActionName(YourViewModel yvm)
{
if (ModelState.IsValid) {
RedirectToAction("OtherAction", "OtherController")
}
return View(yvm);
}
Do you mean you want to do a post, have it bind to the viewmodel for validation purposes in one controller, and then have that controller post to another controller that verifies everything? If so, I suggest taking a look at this code to post in c# http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx.
Edit: Or you could just place the data in a tempdata object if the other controller action doesn't truly require a post.
Edit 2: Wait, is the question how to do the post with jquery? If so,
$("#YourForm").submit(function () {
$.post('#Url.Action("WhateverActionName", "YourController")';
});
});
Note: may be small syntax errors, but close to that. The #Url.Action is the important part.
Edit 3: This should finally work.
jQuery.extend({
postJSON: function(url, data, callback) {
return jQuery.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: callback,
dataType: "json",
contentType: "application/json",
processData: false
});
}
});
Call it in your view as
$.postJSON('#URL.Action("Action", "Controller")', yourJson, callback)
And then redirect inside the controller.
Im creating a simple "Was this useful?" form with Yes and No objects- Using ASP.net webforms.
I need the submission to be done via ajax using jquery, to prevent a user from voting multiple times on the same page.. currently i have two methods Like_Click and Dislike_click in the C# code behind the page in question.
Can anyone give me some pointers on or a link to any suitable walkthroughs for simple ajax via jquery (I'm new to ajax!)
Ive looked at using the [WebMethod] identifier on each of the methods but do not really understand this method fully.
thanks
You are probably looking for jQuery's post function. Check out the examples. You'll want to do something along the lines of:
$('.myForm').submit(function(){ //define a handler for the submit event of the form
$.post($(this).attr('action'), {useful: true}); //send data via ajax
return false; //prevents the form from submitting via a normal web request
});
You can try something like below
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var like = $('#Like').val();
var dislike = $('#Dislike').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home.aspx/UpdateDB', //UpdateDB is declared as WebMethod
async: false,
data: "{'like':'" + like + "','dislike':'" + dislike + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#Like').val('');
$('#Dislike').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
Webmethod is shown below
[WebMethod]
public static string UpdateDB(string like, string dislike)
{
//Add your stuff
}
take a look more details here Call WebMethod from jquery in ASP.NET
I'm trying to send my form to a web method in asp.net page using jquery.forms plugin (primary reason for that is that I need to send files as well).
However, I can't make it work - it returns the whole page all the time.
I use the following client-side code:
<script type="text/javascript">
var ajaxUploadOptions = {
beforeSubmit: UploadFormValidate, // pre-submit callback
success: FormUploadSuccess, // post-submit callback
error: FormUploadFailure,
url: "Default.aspx/UploadFiles", // override for form's 'action' attribute
type: "POST", // 'get' or 'post', override for form's 'method' attribute
dataType: "json", // 'xml', 'script', or 'json' (expected server response type)
contentType: "application/json; charset=utf-8",
};
function FormUploadSuccess(response, statusText, xhr, jqForm) {
alert(response);
};
function FormUploadFailure(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
$("form[id $= 'form1']").ajaxForm(ajaxUploadOptions);
});
</script>
Code for the asp.net method just to return anything:
[WebMethod]
public static string UploadFiles()
{
return "Test";
}
I registered ScriptModule in web.config (also verified just calling regular jquery's $.ajax to make sure the method is available).
Any suggestions would be appreciated.
Thanks!
It seems I haven't read documentation/code carefully enough. Found out that when sending files, the forms plugin uses iframe and regular submit.