0

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);
}
2
  • Hi, what is your question or your error? To post to another controller; create controller and an action. Use those in the @Url. statement. Commented Jan 24, 2016 at 18:28
  • i want get title and price of object that clicked and send title and price to another controller Commented Jan 24, 2016 at 18:32

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

6 Comments

Are you getting any script errors ? Are you sure you are able to read the values from your DOM for titleVal and priceVal variables ?
but the error method just runing and alert('error')
Take a look at my updated answer. You need to fix your action method.
I tried the exact code in the answer with hard coded values for the two variables and it worked for me. So I guess you have some other script error in your page. Check your browser console.
now i want return view in Item method how do this?when i try return view(); not work
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.