Reputation: 1790
I want to call the action method(AddCompare) using an Ajax request at the View,
My problem is that the parameter sent to AddCompare Action always has zero value, While the parameter value in the function AddToCompare is correct
this is my code
View:
@model IEnumerable<Products>
@foreach (var item in Model)
{
<li>
<div class="left-block">
<div class="quick-view">
<a title="Add To Compare" class="heart" href="#" onclick="AddToCompare(15)"></a>
</div>
</div>
</li>
}
<script>
function AddToCompare(param) {
alert(param); //display correct value 15
$.ajax({
type: "GET",
url: "@Url.Action("AddCompare")",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
id: param
}),
success: function (response) {
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
</script>
Controller
public JsonResult AddCompare(int id)
{
//id is zero !!!
int param=id;
}
Where is the problem?
Upvotes: 3
Views: 1062
Reputation: 1554
try to use
$.get
this is the syntax
$.get(URL,data,function(data,status,xhr),dataType)
Upvotes: 1
Reputation: 62
Since you are using a Get verb you can do this:
$.ajax({
type: "GET",
url: "/Controller/Action?ID=" + id,
dataType: "json"
}).done(function (response) {
//response code here
});
Change the controller and the action to your needs and you can add other settings to the ajax if needed.
Upvotes: 0
Reputation: 2263
In your AJAX call you don't need to stringify
$.ajax({
// your code
data: {id: param},
Decorate your action method with HttpGet
even if it is GET
by default. Just a better practice.
[HttpGet]
public JsonResult AddCompare(int id)
{
}
Upvotes: 0