Razor在javascript中查看if / else语句

时间:2014-11-06 11:57:58

标签: javascript asp.net-mvc asp.net-mvc-4 razor

是否可以在剃须刀视图中执行此操作。我只想在声明为真的情况下注入JavaScript以下。我怎么能这样做。

            @if (Model.EmployeeInterviews != null)
            {
                $("#select-Candidate")[0].selectize.setValue(@Html.Raw(JsonConvert.SerializeObject(Model.CandidateId)));
                var employee = @Html.Raw(JsonConvert.SerializeObject(selectedempobj));
                var val = "[";
                for (i = 0; i < employee.length; i++)
                {
                    val += employee[i].EmployeeID + ",";
                }
                val = val.substring(0, val.length - 1) + "]";

                $("#select-Employee")[0].selectize.setValue(JSON.parse(val));
                $('#txtScheduledOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.ScheduledOn)');
                $('#txtCompletedOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.CompletedOn)');
                $('#hdnEmployeeId').val(JSON.parse(val).toString());
                $('#hdnCandidateId').val('@Html.Raw(JsonConvert.SerializeObject(Model.CandidateId))');
            }

2 个答案:

答案 0 :(得分:5)

像这样的东西

<script type="text/javascript">
    $(document).ready(function () {
        //... some common javascript

        @{
            if (Model.EmployeeInterviews != null) {
            <text>
            $("#select-Employee")[0].selectize.setValue(JSON.parse(val));
            $('#txtScheduledOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.ScheduledOn)');
            //... specific javascript
            </text>
            }
        }
    });
</script>

答案 1 :(得分:2)

尝试以下

@if (Model.EmployeeInterviews != null)
{
    <script type="text/javascript">
        $("#select-Candidate")[0].selectize.setValue(@Html.Raw(JsonConvert.SerializeObject(Model.CandidateId)));
        @{
            IHtmlString employee = @Html.Raw(JsonConvert.SerializeObject(selectedempobj));
         }
        string val = "[";
        for (int i = 0; i < employee.length; i++)
        {
            val += employee[i].EmployeeID + ",";
        }
        val = val.substring(0, val.length - 1) + "]";

        $("#select-Employee")[0].selectize.setValue(JSON.parse(val));
        $('#txtScheduledOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.ScheduledOn)');
                $('#txtCompletedOn').val('@String.Format("{0:M/d/yyyy HH:mm tt}", Model.CompletedOn)');
                $('#hdnEmployeeId').val(JSON.parse(val).toString());
                $('#hdnCandidateId').val('@Html.Raw(JsonConvert.SerializeObject(Model.CandidateId))');
    </script>
}