Ansar Maleki
Ansar Maleki

Reputation: 41

Sending data from View to another Controller using JQuery

I want to send data from view to another controller using JQuery

var title;
var price;
var container;
$('a.btn').click(function () {
    container = $(this).closest('.item');
    title = container.find('.item-dtls > h4 > a').text();
    price = container.find('.price').text(); 
});

$('a.btn').click(function () {
    $.ajax({
        url: '@(Url.Action("Item", "Home"))',
        type:'POST',
        datatype:text,
        data:{title,price},
        success: function (data) {
            alert('success');
        },
        error: function (data) {
            alert('error');
        }
    });
});

This is my controller

[HttpPost]
public ActionResult Item(string title,string price) {
    Response.Write(title);
}

Upvotes: 0

Views: 536

Answers (1)

Shyju
Shyju

Reputation: 218732

Send the data as name-value pairs. Also you do not need two separate click event handlers.

Also, the datatype property value should be a string. so wrap that in single/double quotes.

$('a.btn').click(function () {
     var container = $(this).closest('.item');

     var titleVal = container.find('.item-dtls > h4 > a').text();
     var priceVal = container.find('.price').text(); 

     alert(titleVal);
     alert(priceVal);
     $.ajax({
         url: '@Url.Action("Item", "Home")',
         type:'POST',
         datatype:'text',
         data: { title : titleVal , price : priceVal },
         success: function (data) {
             alert('success');
             alert(data);
         },
         error: function (data) {
             alert('error'); }
         });
     });

});

Also, You cannot use Response.Write to return something from your action method. You can use Content method to return a string.

[HttpPost]
public ActionResult Item(string title, string price)
{        
    return Content(title);
}

Upvotes: 2

Related Questions