Reputation: 613
So, i works in a project and i have a problem when i pass data from my view to my javascript,i have a foreach loop but always i get the last elements, this is my view :
@foreach (var al in Model.alerts)
{
<table border="0">
<tr>
<td rowspan=3><img src= '@Html.Raw(al.Owpicture)' class="img" alt="IMAGES"/></td>
<td><label class="lb">@Html.Raw(al.cinOw)</label></td>
</tr>
<tr>
<td><label class="lb">@Html.Raw(al.Owname)</label></td>
</tr>
<tr>
<td><label class="lb">@Html.Raw(al.OwpermitNumber)</label></td>
</tr>
</table>
<script>
//this is variable to pass
var carNum = '@Html.Raw(al.carNumber)';
</script>
<input type="submit" name="Report" value="Report" onclick="IsReport(carNum)" />
and this is my script code :
function IsReport(carNum)
{
var url = '/Home/IsReport/' + carNum;
$.ajax({
type: "Post",
url: url,
data: {},
datatype: 'json',
success: function (data) { alert(carNum); },
});
}
i tried everything but always i get the last carNum, so please if someone have any idea i will be very appreciate .
Upvotes: 2
Views: 9961
Reputation:
function IsReport()
{
$.ajax({
type:"Post",
url:'/Home/IsReport/' + carNum,
datatype:'json',
success:function (data) { alert(data.carNum); },
});
}
The above answer display's the data.carNum
value.
Upvotes: 0
Reputation: 123739
You need to try this way:-
<input type="submit" name="Report" value="Report" onclick="IsReport(@Html.Raw(al.carNumber))" />
What happens here in your code is that every iteration it will put the following in your html. and when you refer to the variable carnum
it has the value from the last iteration.
<script>
//this is variable to pass
var carNum = '@Html.Raw(al.carNumber)';
</script>
Another way is to use data attribute instead of using onclick event:-
<input type="submit" name="Report" value="Report" data-carnum="@al.carNumber" />
and in your script
$(function(){
$("input[name=Report]").on('click',function(){
....//some code
IsReport($(this).data('carnum'));
...///some code
});
});
Upvotes: 4