我一直在寻找这一天的答案,并认为这将是一件简单的事情。
我有以下代码填充数据库中的下拉框,一切正常,填充下拉列表并在选择文章后自动提交表单,但它不会返回参数或告诉ViewResults操作选择项目的方法,因此我在null中得到“id”错误。如果我手动将“id”的数字添加到URL字符串中,则一切正常。
控制器方法:
public ActionResult Index()
{
var db = new MvcFourEntities();
var query = db.Articles.Select(c => new { c.ArticleID, c.ArticleName });
ViewBag.ArticleId = new SelectList(query.AsEnumerable(), "ArticleID", "ArticleName", 0);
return View(db.Articles.ToList());
}
public ViewResult Details(int id)
{
Article article = db.Articles.Single(a => a.ArticleID == id);
return View(article);
}
在视图中下拉列表有两种不同的形式,一种是通过jQuery提交而另一种是不通过,也没有传递参数:
jQuery提交:
@using (Html.BeginForm("Details", "Article", FormMethod.Post, new { id = "TheForm" })){
@Html.DropDownList("ArticleID", (SelectList)ViewBag.ArticleId, "Please Select an Article")
}
非jQuery提交:
@using (Html.BeginForm("Details", "Article", FormMethod.Post, new { id = "TheForm" }))
{
@Html.DropDownList(
"ArticleID",
(SelectList)ViewData["Articles"],
"Please Select an Article",
new
{
onchange = "document.getElementById('TheForm').submit();"
})
}
我一直在关注此处的教程:http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists
我哪里出错了?
干杯,
麦克
答案 0 :(得分:0)
在对Html.DropDownList
的两次调用中,您都将选择的名称设为ArticleID
。您需要将其更改为id
。
@using (Html.BeginForm("Details", "Article", FormMethod.Post, new { id = "TheForm" })){
// The first parameter has been changed from "ArticleID" to "id"
@Html.DropDownList("id", (SelectList)ViewBag.ArticleId, "Please Select an Article")
}
请参阅MSDN文档。
答案 1 :(得分:0)
John Allers撰写的黑客作品
<script type="text/javascript">
$(function () {
$("#ArticleID").change(function () {
var actionUrl = $('#TheForm').attr('action') + '/' + $('#ArticleID').val();
$('#TheForm').attr('action', actionUrl);
$('#TheForm').submit();
});
});
</script>