Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC and JQuery get info to controller

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.

like image 832
Buddy Lindsey Avatar asked Jan 05 '09 22:01

Buddy Lindsey


2 Answers

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.

like image 179
foxxtrot Avatar answered Sep 28 '22 05:09

foxxtrot


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) { }
        });
like image 23
Jack1987 Avatar answered Sep 28 '22 05:09

Jack1987