I am totally confused on how to do ajax stuffs with jQuery and it seems the more I try the more confused I get. At this point all I want to do is get data to my controller using jQuery ajax. Some code for my jquery ajax call is.
$(function() {
$('#buttonAddLink').click(function() {
var AjaxLink = {
title: $("#linkTitle").val(),
url: $("#linkUrl").val()
};
$.ajax({
url: '/User/AddLink',
type: 'POST',
data: AjaxLink,
dataType: 'json',
success: function(result){
$('.added').html(result.Result).show();
}
});
});
});
Here is my controller and Action I am using. From trying to look at several tutorials it "should" work to the best of my knowledge, but apparently I don't get it like I thought I did.
public ActionResult AddLink(string title, string url)
{
return Json(new { Result = string.Format(title + " " + url)});
}
All I am basically trying to do with that is do the Ajax call and return it to display just to make sure data was sent to the controller.
It has to do with the way you're structuring your request. Your JQuery call is sending the data to the AddLink action on the User controller as POST data, which means in your C# code, you'll access it via the Request.Form object. With what you're trying to do, you'd structure the jQuery URL as
/User/AddLink/{Title}/{URL}
This would require you to write a rule in your Global.ASAX file that handled that sort of input. In short, if you just modify your AddLink method as follows:
public ActionResult AddLink()
{
return Json(new { Result = string.Format(Request.Form["title"] + " " + Request.Form["url"])});
}
I believe you'll get the response you're looking for.
Ok, try this code using Ajax to pass data to your action method:
jQuery.ajax({
url: '@Url.Action("AddLink", "User")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ title: title, url: url }),
success: function (result) { }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With