从 html.listbox 中获取所选项目,而无需在 MVC 中发布帖子
本文关键字:MVC 布帖 listbox html 获取 项目 选项 | 更新日期: 2023-09-27 17:55:56
我正在从MVC开始,但这就是我想要的。
我的一侧有一个项目列表,另一侧有一个文本框。我想单击列表中的一个项目,让文本框显示该项目的文本,但不要使用按钮或帖子;类似于" OnSelectedIndexChanged
"。
这就是我目前所拥有的。
控制器:
public ActionResult Index()
{
var model = new TestModel();
model.ListOfItems = new List<SelectListItem>();
SelectListItem item = new SelectListItem();
item.Text = "Item's text";
item.Value = "Value for the list";
model.ListOfItems.Add(item);
return View(model);
}
型:
public int[] ItemId { get; set; }
public List<SelectListItem> ListOfItems { get; set; }
视图:
<script type="text/javascript">
function showText() {
var selectedItem = itemsList.options.selectedIndex;
txtValue.Text = selectedItem.value;
}
</script>
<h2>Test</h2>
@Html.ListBoxFor(x => x.ItemId, new MultiSelectList(Model.ListOfItems, "Text", "Value", Model.ItemId), new { size = 6, id = "itemsList", OnChange = "showText" })
@Html.TextBox("itemText", "", new { id = "txtItem" })
有一些 javascript 来侦听列表框上的点击事件并获取项目文本并设置为另一个文本框的值
$(function(){
$("#ItemId option").click(function () {
var _this = $(this);
$("#txtItem").val($(_this).text());
});
});
工作样品 : http://jsfiddle.net/w4sxw/
假设你已经将jQuery加载到页面。