Reputation: 150
I have a view that is generated by a model as a list of tasks. When clicking on a certain task I want my javascript function to receive a variable with a different value to execute.
@model IEnumerable<CreateAndApproveStockCode.Models.Task>
<h3>Tasks</h3>
@if (Model != null)
{
int num = 0;
foreach (var task in Model)
{
num = task.num;
<div class="tasksclick" onclick="callDetail("+num+")">
<div class="taskname">
@Html.DisplayFor(taskitem => task.name)
</div>
<div class="taskdes">
@Html.DisplayFor(taskitem => task.description)
</div>
</div>
}
}
<script type="text/javascript">
function callDetail(d)
{
var serviceUrl = "/Detail/Populate?d="+d;
var request = $.post(serviceUrl);
request.done(
function (data)
{
$("#detail").html(data);
}
);
}
</script>
The num variable receives from the task model its value and this value needs to be passed to the javascript variable d so that the detail view can be refreshed according to this value, however nothing happens.
Upvotes: 1
Views: 7843
Reputation: 23
Just keep in mind that whenever we have to use c# code in a cshtml file, we always use @ before writing our code. Just like you have used @ before if(). Now because num is a C# variable, so use @ with it like this: @num
Secondly, since you want to pass to string value, so use '' around it. So, resultant code is:
<div class="tasksclick" onclick="callDetail('@num')">
Upvotes: 0
Reputation: 7506
Since num
is a C# variable and you're mixing HTML and "regular" code, you need to tell the compiler that you're referencing a variable that it manages. Don't concatenate strings, just add the @
:
<div class="tasksclick" onclick="callDetail(@num)">
or, if you want to pass a string parameter (which is probably what you really want):
<div class="tasksclick" onclick="callDetail('@num')">
Upvotes: 3