将值从ViewModel传递到JavaScript

时间:2015-02-25 23:17:39

标签: javascript c# jquery model-view-controller

我正在创建一个MVC 5 Web应用程序,我希望将我的ViewModel中的值传递给我的JavaScript中的函数

当用户选择选项"否"时,目标是隐藏标签/分区。当用户将选项更改回"是"

时,使其重新出现

这是我到目前为止所做的:

视图模型:

public enum BasicAnswer
        {
            [Display(Name= "Yes")]
            Yes,
            [Display(Name= "No")]
            No
        }
 public BasicAnswer userDiscomfortResponse { get; set; }

查看:

   <div id="UserDiscomfortAnswerLabel">
            <label id="somelabel">Did you have any discomfort with an exercise?</label>
            <div class="Answer1" onclick=feedback data-id='@Model.userDiscomfortResponse'>
                @Html.EnumDropDownListFor(m => m.userDiscomfortResponse, new { @class = "form-control" })
        </div>
    </div>

    <div class="Question2">
        <label id="UserDiscomfortExerciseLabel">What exercise was the issue?</label> 
        <div class="Answer2">
            @Html.DropDownListFor(m => m.discomfortExercise, Model.UsersSelectedExcerises, new { @class = "form-control" })
        </div>
    </div>

JavaScript的:

function feedback() {
    var feedback = $(this).attr('data-id'); 
    if (feedback == "Yes") {
        document.getElementById("UserDiscomfortExerciseLabel").style.display = "block"
    }
    else {
        document.getElementById("UserDiscomfortExerciseLabel").style.display = "none"
    }
}

我遇到的问题是var feedback = $(this).attr(&#39; data-id&#39;)结果为未定义,因此标签隐藏在点击上但从未再次显示。

有没有我错过的东西?

提前谢谢。

1 个答案:

答案 0 :(得分:0)

好的,尝试删除div上的onclick并添加:

$(document).ready(function()
{
    function feedback() {
        var feedback = $('#userDiscomfortResponse').val()
        if (feedback == "Yes") {
            document.getElementById("UserDiscomfortExerciseLabel").style.display = "block"
        }
       else {
           document.getElementById("UserDiscomfortExerciseLabel").style.display = "none"
       }
    }

    $("#userDiscomfortResponse").change(feedback);
    feedback();
}