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.
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.
Share Improve this question asked Jan 24, 2014 at 8:49 tvmannetjietvmannetjie 1501 gold badge2 silver badges13 bronze badges2 Answers
Reset to default 3Since num
is a C# variable and you're mixing HTML and "regular" code, you need to tell the piler 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')">
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')">
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745636897a4637450.html
评论列表(0条)