gpt4 book ai didi

c# - 从 MVC 中的 FormCollection 中获取选定的下拉列表值

转载 作者:太空狗 更新时间:2023-10-29 13:26:58 26 4
gpt4 key购买 nike

我有一个表单发布到一个带有 MVC 的 Action 。我想从操作中的 FormCollection 中拉出选定的下拉列表项。我该怎么做?

我的 Html 表单:

<% using (Html.BeginForm())
{%>
<select name="Content List">
<% foreach (String name in (ViewData["names"] as IQueryable<String>)) { %>
<option value="<%= name %>"><%= name%></option>
<% } %>
</select>
<p><input type="submit" value="Save" /></p>
<% } %>

我的行动:

[HttpPost]
public ActionResult Index(FormCollection collection)
{
//how do I get the selected drop down list value?
String name = collection.AllKeys.Single();
return RedirectToAction("Details", name);
}

最佳答案

首先为您的 select 标签提供一个有效的 name。有效名称不能包含空格。

<select name="contentList">

然后从表单参数集合中获取选定的值:

var value = collection["contentList"];

甚至更好:不要使用任何集合,使用与您的选择名称同名的操作参数,并保留默认模型绑定(bind)器填充它:

[HttpPost]
public ActionResult Index(string contentList)
{
// contentList will contain the selected value
return RedirectToAction("Details", contentList);
}

关于c# - 从 MVC 中的 FormCollection 中获取选定的下拉列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004788/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com