2016-03-03 93 views
0

我有一个下拉列表,我在其中调用js函数,在change事件上。 在查看:将ViewBag传递给js函数

@Html.DropDownList("RaceId", ViewData["Races"] as List<SelectListItem>, new { @onchange = "CallChangefunc(this.value)", @class="form-control" }) 

和我的JS:

<script> 
function CallChangefunc(val) 
{ 
//called in Index page when dropdown list changes 
window.location.href = "/Index/" + val; 
} 
</script> 

我要的是一个新的参数添加到我的js函数,我传递一个ViewBag值,某事像:

@Html.DropDownList("RaceId", ViewData["Races"] as List<SelectListItem>, new { @onchange = "CallChangefunc(this.value,ViewBag.id)", @class="form-control" }) 

上述不起作用,我不确定哪个是正确的语法,如果有的话。

+1

使用[非侵入式JavaScript](https://en.wikipedia.org/wiki/Unobtrusive_JavaScript)(其在21世纪) - '$(#RaceId')。改变(函数(){var val = $(this).val(); var id ='@ ViewBag.id'; ......});' –

+0

@ stephenmuecke的评论需要jQuery,并且应该读$('#RaceId').....但他说得很好! – wazdev

回答

0

首先,使用unobtrusive javascript而不是onchange attribute。如果你有你的观点里面你的JavaScript,您可以访问ViewBag也使用'@ViewBag'

$('#RaceId').on('change', function() 
    { 
     var value = $(this).val(); 
     var id = '@ViewBag.id' 
    } 
); 

或者,如果你在不同的文件运行你的JavaScript,你可以使用一个Hidden input并在脚本中获取此值:

@Html.Hidden("Id", ViewBag.id) 

和你的脚本:

$('#RaceId').on('change', function() 
    { 
     var value = $(this).val(); 
     var id = $("Id").val(); 
    } 
); 
0

尽管斯蒂芬的评论是100%正确的,我只想想知道,如果这能解决你的问题:

@{ 
    var htmlAttr = new Dictionary<string, object>(); 
    htmlAttr.Add("onchange", string.Format("{0}{1})", "CallChangefunc(this.value", @ViewBag.id)); 
        htmlAttr.Add("class", "form-control"); 
    } 
    @Html.DropDownList("RaceId", ViewData["Races"] as List<SelectListItem>, @htmlAttr)