【发布时间】:2011-03-22 19:35:32
【问题描述】:
在我看来,我有一个通过 Ajax 调用填充的下拉列表。此下拉列表在表单内。然而在提交时,我在 formCollection 中看不到这个控件。
还有一件事,或者当我尝试添加 Html.DropDownList("AccountId") 时,我收到错误 - 没有具有键 'AccountId' 的 'IEnumerable' 类型的 ViewData 项。
列出了我的视图和控制器代码...
--查看--
using (Html.BeginForm("GetNames", "Account", FormMethod.Post, new { id = "accountParameters" }))
{
....
....
<select id="AccountId" runat="server"></select> //This is not available in formcollection
//Html.DropDownList("AccountId"); //This throws exception
@:<p><input type='submit' value='Submit'/></p>
}
...
...
<script>
$(document).ready(function () {
$.ajax({
url: '/Account/GetAccounts',
type: "GET",
success: function (result) {
for (i = 0; i < result.length; i++) {
$('#AccountId').append($('<option></option>').val(result[i].accountId).html(result[i].name));
}
}
});
});
</script>
-- 控制器--
public ActionResult GetAccounts(string id)
{
return Json(GetAccounts(), JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetNames(FormCollection formCollection)
{
if (("AccountId") != null)
{
....
....
}
}
【问题讨论】:
-
Ajax 调用是否有效?即页面加载时是否填写表格?
-
是的。我在 Select 元素中获取项目
标签: jquery asp.net-mvc-3 razor