尝试将函数应用于我的MVC4表单中的下拉列表。然而,变量周围的“'”仍然在HTML中呈现为“&#39”。显然对于javascript这不是我的意思。我目前使用以下代码:
@Html.DropDownListFor(t => t.tabPosition, new SelectList(ViewBag.DdlPositions), new { onclick = Html.Raw("ddlChain(this.id, '" + Html.DisplayNameFor(t => t.relTab) + "', '')") })
并且生成的html看起来像
<select id="tabPosition" name="tabPosition" onclick="ddlChain(this.id, 'relTab, '')">
<option>Start</option>
<option>End</option>
<option>Before</option>
<option>After</option>
</select>
或者有更好的方法将js函数分配给MVC中的输入吗?
由于
答案 0 :(得分:0)
最好通过模型而不是通过ViewBag传递列表。与@SLaks一起回答将这个放在你的脚本中
$(document).ready(function(){
$('#tabPosition').on('change', function(){
//Your code here for the change event something like
$('.Selected').val($('#tabPosition :selected').val());
//which will set an field on your page with class="Selected" to the selected item from your dropdown
});
});
答案 1 :(得分:0)
将代码的第一部分更改为:
@Html.DropDownListFor(t => t.tabPosition, new SelectList(ViewBag.DdlPositions), new Dictionary<string,string>{{ "data-tab", Model.relTab }})
使用select element
属性创建data-tab
。
现在,我们只需要创建一个javascript来阅读data-tab
值并调用您的ddlChain
函数。
$('#tabPosition').on('change', function() {
var $this = $(this);
ddlChain($this.attr('id'), $this.attr('data-tab'), '');
});