Reputation: 669
Been struggling with this for over a day, how can I pass an actionlink id to a jquery ajax call to enable a partial page update.
<li>@Html.ActionLink(@item.strCountry, "Index", "Weather", new { id = Regex.Replace(@item.strCountry, " ", "-") }, new { @class = "getCities" })</li>
jQuery
<script>
$(function () {
$(".getCities").click(function () {
$.ajax({
//url: this.href,
url: '@Url.Action("pvDisplayListOfWeatherCities", "Weather")',
type: 'GET',
data: { id: $('#id').val() },
dataType: 'Json',
success: function (result) {
alert(result.test);
},
error: function () {
alert("error");
}
});
return false;
});
});
</script>
Thanks
George
Upvotes: 0
Views: 2689
Reputation: 2942
Add the parameter(s) as HTML attribute(s)
<li>@Html.ActionLink(@item.strCountry, "Index", "Weather",
new { id = Regex.Replace(@item.strCountry, " ", "-") },
new { @class = "getCities", data_param1 = Regex.Replace(@item.strCountry, " ", "-") })</li>
this will render:
<li><a class="getCities" href="/Weather/Index/val" data-param1="val">country</a></li>
and then use the jQuery .attr()
method:
<script>
$(function () {
$(".getCities").click(function () {
$.ajax({
//url: this.href,
url: '@Url.Action("pvDisplayListOfWeatherCities", "Weather")',
type: 'GET',
data: { id: $(this).attr("data-param1") }, // <-- param1 etc.
dataType: 'json',
success: function (result) {
alert(result.test);
},
error: function () {
alert("error");
}
});
return false;
});
});
</script>
Upvotes: 1
Reputation: 3404
You're not setting id
attribute for this link, you're just setting id that is used as a parameter to build link itself. You should simply add id
attribute for this tag
<li>@Html.ActionLink(@item.strCountry, "Index", "Weather",
new { id = Regex.Replace(@item.strCountry, " ", "-") },
new { @class = "getCities", @id = Regex.Replace(@item.strCountry, " ", "-")})</li>
if you want it to be the same as id
of parameter in your link. And then update this
data: { id: $('#id').val() },
to this
data: { id: $(this).attr('id') },
to get the actual id
attribute of this HTML tag.
Upvotes: 1
Reputation: 4908
If I understood the question correctly then you change:
data: { id: $('#id').val() },
to
data: { id: $(this).attr('id') },
Edit - all you need is data: { id: $(this).text() },
Upvotes: 1