的FormCollection不含&LT;选择&GT;控制MVC剃刀加 [英] FormCollection not containing <select> control added in MVC Razor
问题描述
在我看来,我有一个下拉菜单,我通过Ajax调用填充。该下拉列表的形式之内。然而上提交,我没有看到的FormCollection此控件。
还有一件事,或者,当我尝试添加Html.DropDownList(帐户ID),我得到的错误 - 有型'的IEnumerable具有关键的无ViewData的项目'ACCOUNTID。
上市我的视图和控制器code ...
- 视图 -
使用(Html.BeginForm(GetNames,帐户,FormMethod.Post,新{ID =accountParameters}))
{
....
....
&LT;选择一个id =ACCOUNTID=服务器&GT;&LT; /选择&GT; //这不是的FormCollection可用
//Html.DropDownList(\"AccountId); //这引发异常 @:其中,P&GT;&LT;输入类型=提交值=提交/&GT;&LT; / P&GT;
}
...
...
&LT;脚本&GT;
$(文件)。就绪(函数(){
$阿贾克斯({
网址:'/帐号/ GetAccounts',
键入:GET,
成功:函数(结果){
对于(i = 0; I&LT; result.length;我++){
$('#AccountId').append($('<option></option>').val(result[i].accountId).html(result[i].name));
}
}
});
});
&LT; / SCRIPT&GT;
- 控制器 -
公众的ActionResult GetAccounts(字符串ID)
{
返回JSON(GetAccounts(),JsonRequestBehavior.AllowGet);
}的[AcceptVerbs(HttpVerbs.Post)
公众的ActionResult GetNames(的FormCollection的FormCollection)
{
如果((帐户ID)!= NULL)
{
....
....
}}
元素需要name属性在POST请求被发回,你必须改变你的选择是这样的(也降=服务器):
&LT;选择一个id =ACCOUNTIDNAME =ACCOUNTID&GT;&LT; /选择&GT;
In my view, I have a dropdown which I fill via Ajax call. This dropdown is within the form. Yet on submit, I don't see this control in the formCollection.
One more thing, alternatively when I try to add Html.DropDownList("AccountId"), I get error - There is no ViewData item of type 'IEnumerable' that has the key 'AccountId'.
Listed my View and controller code...
--View--
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>
-- Controller --
public ActionResult GetAccounts(string id)
{
return Json(GetAccounts(), JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetNames(FormCollection formCollection)
{
if (("AccountId") != null)
{
....
....
}
}
Element needs name attribute to be send back in POST request, you have to change your select like this (also drop the runat="server"):
<select id="AccountId" name="AccountId"></select>
这篇关于的FormCollection不含&LT;选择&GT;控制MVC剃刀加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!