Html.DropDownListFor 后台取值

feng199 2017-03-09 12:09:07
model:

public class RegisterViewModel
{
public IEnumerable<SelectListItem> aaa { get ; set; }
}

-------------------------------------------------------------------------------------------------------------------
view:

@Html.DropDownListFor(m => m.aaa, ViewData["d"] as SelectList)

-------------------------------------------------------------------------------------------------------------------
controls:

public ActionResult Register()
{
List<SelectListItem> items = new List<SelectListItem>()
{
new SelectListItem(){Text="a", Value="a1", Selected = true},
new SelectListItem(){Text="b", Value="b1"},
};

ViewData["d"] = new SelectList(items, "Value", "Text");
return View();
}

[HttpPost]
public async Task<ActionResult> Register(RegisterViewModel model)
{
IEnumerable<SelectListItem> s = model.aaa as IEnumerable<SelectListItem>;

if (s != null)
{
int i = -1;
foreach (SelectListItem sli in s)
{
i++;
}
Response.Write("<script type='text/javascript'>alert('" + i.ToString () + " ');</script >");
}
}


-------------------------------------------------------------------------------------------------------------------

这里后台post,无法取到数据?
...全文
468 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
feng199 2017-03-15
  • 打赏
  • 举报
回复
view:

 @Html.DropDownListFor(d => d.aaa, Model.Select,"-- select --")
运行后,html:

            <select id="aaa" name="aaa"><option value="">-- select --</option>
<option selected="selected" value="a1">a</option>
<option value="b1">b</option>
</select>
model:
   public class RegisterViewModel
    {
        public string aaa { get; set; }

    }
报错: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'aaa'.”
xiaojunjor 2017-03-13
  • 打赏
  • 举报
回复
model里添加 public int aaaId { get ; set; } @Html.DropDownListFor(m => m.aaaId, ViewData["d"] as SelectList) 然后后台直接model.aaaId就去到a1或者b1了。 DropDownListFor上应该绑定的是你下拉选选中的那个值,而不是整个集合
feng199 2017-03-12
  • 打赏
  • 举报
回复
只提交选中的那个option的value 提交到后台后,对应你这里的a1或者b1, 那后台如何取到 a1 或者 b1
  • 打赏
  • 举报
回复
你的理解有问题,SelectList或者IEnumerable<SelectListItem>是服务端的,用来绑定下拉选项列表的 而在浏览器页面上,生成的是html中select,它就跟input一样,只提交选中的那个option的value 提交到后台后,对应你这里的a1或者b1,显然是没法转换成IEnumerable<SelectListItem> aaa的 如果你实在要那么做,可以弄成json,放在hidden中,然后自己反序列化
feng199 2017-03-09
  • 打赏
  • 举报
回复
谢谢您! 那后台如何获取到 被选中的text

62,074

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧