Search code examples
javascriptasp.net-mvcvariables

onclick with variable in it mvc 4


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.


Solution

  • 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')">