【发布时间】:2016-05-02 00:05:22
【问题描述】:
我有多个使用 for 循环呈现的下拉列表,我在让它们将所选值发布到控制器时遇到问题。在我的查询中,我的选择列表是这样的:
model.CreateGroupForm.Genders = new List<SelectListItem>
{
new SelectListItem() {Text = "Either", Value = "Either"},
new SelectListItem() {Text = "Male", Value = "Male"},
new SelectListItem() {Text = "Female", Value = "Female"},
};
我的第一个问题甚至是让我的下拉菜单显示数据库值,尽管我确认它正在检索正确的值。它不适用于此:
@for (var c = 0; c < Model.ExistingGroups.Count; c++)
{
@using (Html.BeginForm("EditGroup", "Group", new { id = Model.Id.StripCollectionName(), slug = Model.Slug, innerid = Model.ExistingGroups[c].Id }, FormMethod.Post, new { id = "editcommunityteamform" + c.ToString(CultureInfo.InvariantCulture), @class = "nomarginbottom" }))
{
...
@Html.DropDownListFor(x => x.ExistingGroups[c].Gender, Model.Createform.Genders)
<button type="submit" class="btn btn-primary" title="Update name and description of this group">Update</button>
}
}
在对 Stack 进行了一些挖掘之后,我发现呈现的每个下拉列表都需要它自己的单独列表。所以我把它改成:
@Html.DropDownListFor(x => x.ExistingGroups[c].Gender,
new SelectList( Model.CreateGroupForm.Genders,"Value", "Text",Model.ExistingGroups[c].Gender))
这会正确显示查询的值,但是当我提交表单时它只是将 null 发布到控制器。我在 for 循环中使用 checkboxfor boolean 时遇到了同样的问题。
控制器中的我的 ActionResult 只需要一个字符串值,如下所示:
public ActionResult EditGroup(EditGroupInput input)
{
var command = new EditGroupCommand(input.Gender);
....
我的视图模型如下所示:
public IList<CommunityGroup> ExistingGroups { get; set; }
public CreateGroupInput CreateGroupForm { get; set; }
然后上面2个类就有了代码中提到的属性。
【问题讨论】:
-
当您说发布 null 时,您是否在发布操作中使用相同的织机来获取值。
-
不,actionResult中没有循环,应该有吗?我已经用我目前拥有的内容编辑了 OP。
-
这看起来像 ASP.NET MVC 和 Razor?可能想要添加这些标签,以便吸引熟悉这些技术的人的注意。
-
你需要有相同的循环,这样你才能得到 x.ExistingGroups[c].Gender
-
我真的不明白为什么。提交按钮应该只是发布所选下拉列表的值。每个下拉列表都有一个单独的提交按钮,因此每个按钮应该只发布与其关联的下拉列表的值。
标签: c# asp.net-mvc model-view-controller razor