我是 MVC3 的新手,一直在使用 EF 和“Code First”开发一个小型站点。我正在尝试在处理下拉列表的 View 中做一些事情,并且想知道解决这些问题的最佳方法是什么。我希望用户能够从下拉列表中选择一个规则,并且根据选择的规则,我希望页面上有一个标签来显示规则名称(无需发布)。我还需要能够将选定的规则发送到下一页。我还没有将所有必要的字段添加到 View 中,因为我真的不知道它应该如何工作。我应该如何着手尝试这样做?
我有我的模型:
public class D1K2N3CARule
{
public int ID { get; set; }
[Required]
public int Name { get; set; }
[Required]
public string Rule { get; set; }
public D1K2N3CARule(int name, string rule)
{
Name = name;
Rule = rule;
}
public D1K2N3CARule()
{
Name = 0;
Rule = "";
}
}
我的 View 模型:
public class D1K2N3CARuleViewModel
{
public string SelectedD1K2N3CARuleId { get; set; }
public IEnumerable<D1K2N3CARule> D1K2N3CARules { get; set; }
}
我的 Controller :
public ActionResult Index()
{
var model = new D1K2N3CARuleViewModel
{
D1K2N3CARules = db.D1K2N3DARules
};
return View(model);
}
和我的观点:
'@model CellularAutomata.Models.D1K2N3CARuleViewModel
@{
ViewBag.Title = "Index";
}
<asp:Content id="head" contentplaceholderid="head" runat="server">
<script type="text/javascript">
</script>
</asp:Content>
<h2>Index</h2>
<table>
<tr>
<td>
@Html.DropDownListFor(
x => x.D1K2N3CARules,
new SelectList(Model.D1K2N3CARules, "ID","Rule")
)
</td>
</tr>
</table>'
最佳答案
I want a user to be able to select a rule from the dropdownlist, and depending upon which rule was selected, I would like a label on the page to show the rule name (without posting)
这里你需要javascript。 jQuery 将是这项工作的完美选择。我将从为下拉列表提供确定性 ID 开始,因为如果您在模板中运行此 View ,则可能会向 ID 添加前缀,这会破坏我们的 JavaScript ID 选择器(见下文):
@Html.DropDownListFor(
x => x.D1K2N3CARules,
new SelectList(Model.D1K2N3CARules, "ID", "Rule"),
new { id = "ruleDdl" }
)
然后提供一些将接收所选值的容器:
<div id="ruleValue" />
最后在一个单独的 javascript 文件中订阅下拉列表的更改事件并使用选定的值/文本更新容器:
$(function() {
// subscribe for the change event of the dropdown
$('#ruleDdl').change(function() {
// get the selected text from the dropdown
var selectedText = $(this).find('option:selected').text();
// if you wanted the selected value you could:
// var selectedValue = $(this).val();
// show the value inside the container
$('#ruleValue').html(selectedText);
});
});
I also need to be able to send the selected rule onto the next page.
您可以将下拉菜单放在表单中
@using (Html.BeginForm("NextPage", "Foo"))
{
@Html.DropDownListFor(
x => x.D1K2N3CARules,
new SelectList(Model.D1K2N3CARules, "ID","Rule")
)
<input type="submit" value="Go to the next page" />
}
NextPage Controller 操作将接收选定的值。
关于asp.net-mvc - 了解 DropDownListFor 在 MVC3 中的工作方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5098848/