我是VS 2010和MVC2的新用户。我已经从数据库填充了一个下拉列表。我的HomeControler源代码将是 ` 命名空间SampleControls.Controllers {
public class HomeController : Controller
{
SControlsDataContext data = new SControlsDataContext();
public ActionResult Index()
{
var Emp = from prod in data.Emps
select prod;
ViewData["Emps"] = Emp;
return View();
}
public ActionResult About()
{
return View();
}
}
} `
我的Index.aspx将是
<% using (Html.BeginForm())
{ %>
<%= Html.DropDownList("lstProducts", new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), new { onChange = "onSelectedIndexChanged()" })%>
<% } %>
我想要的是“在SelectedIndexChanged上,所选的值应该显示在标签中。
<script type="text/javascript">
function onSelectedIndexChanged()
{
//i know i should write the code here for binding the dropdown selected value to label... But, i dont know how to do this.
}
</script>
答案 0 :(得分:2)
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("lstProducts",
new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"),
new { onchange = "onSelectedIndexChanged(this.value)" })%>
<% } %>
<div id="foo"></div>
然后:
function onSelectedIndexChanged(value) {
document.getElementById('foo').innerHTML = value;
}
更新:
为了获得所选文字:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("lstProducts",
new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"),
new { onchange = "onSelectedIndexChanged(this)" })%>
<% } %>
function onSelectedIndexChanged(select) {
var text = select.options[select.selectedIndex].text;
document.getElementById('foo').innerHTML = text;
}
更新2:
使用jquery可以实现同样的目的:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList("lstProducts",
new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"),
new { id="myselect" })%>
<% } %>
然后:
$(function() {
$('#myselect').change(function() {
var text = $(this).find('option:selected').text();
$('#foo').html(text);
});
});