gpt4 book ai didi

c# - 当我没有按顺序选择复选框时,POST 到 MVC Controller IEnumerable 嵌套模型为空

转载 作者:行者123 更新时间:2023-11-30 14:27:56 25 4
gpt4 key购买 nike

当我尝试在 Post 中获取值时,当我不按顺序(1、2、3 等)检查时,复选框的值设置为 NULL。

我需要不按顺序选择其中任何一个(即 4、5)。

型号:

public class AssignUsersViewModel
{
[Display(Name = "Check to select")]
public bool Select { get; set; }

public int Id { get; set; }

[Display(Name = "App. Username")]
public string UserName { get; set; }

[Required]
public string GivenName { get; set; }

[Required]
public string Surname { get; set; }

[Display(Name = "Roles")]
public IList<Roles> Roles { get; set; }
}

public class AssignUsersAddModel
{
public bool Select { get; set; }

public int Id { get; set; }

public IEnumerable<SelectedRoles> selectedRoles { get; set; }
}

public class SelectedRoles
{
public string Name { get; set; }
}

CSHTML:

@model IList<AspNetIdentity2DRH.Models.AssignUsersViewModel>
@using (Html.BeginForm("UsersAddToApp", "UsersAdmin", FormMethod.Post))
{
@Html.AntiForgeryToken()
<table class="table">
<tr>
<th>Check for add</th>
<th>Username</th>
<th>Givenname</th>
<th>Surename</th>
<th>Roles</th>
</tr>
@for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>
@Html.CheckBoxFor(x => x[i].Select)
@Html.HiddenFor(x => x[i].Id)
</td>
<td>
@Html.DisplayFor(x => x[i].UserName)
</td>
<td>
@Html.DisplayFor(x => x[i].GivenName)
</td>
<td>
@Html.DisplayFor(x => x[i].Surname)
</td>
<td>
<div class="row">
<div class="form-group">
@for (int j = 0; j < Model[i].Roles.Count(); j++)
{
<div class="col-sm-4">
<input type="checkbox" name="[@i.ToString()].selectedRoles[@j.ToString()].Name" value="@Model[i].Roles[j].Name" class="checkbox-inline" />
@Html.Label(Model[i].Roles[j].Name, new { @class = "control-label", @data_toggle = "tooltip", @data_placement = "top", @data_original_title = Model[i].Roles[j].Description })
</div>
}
</div>
</div>
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Add existing user" class="btn btn-primary" />
<input type="button" value="Cancel" onclick="window.location.href = '@Url.Action("UsersIndex", "UsersAdmin")';" class="btn btn-cancel" />
</p>
}

Controller :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UsersAddToApp(List<AssignUsersAddModel> model)
{
if (ModelState.IsValid)
{
foreach (AssignUsersAddModel item in model)
{
if (item.Select)
{
using (DbContextTransaction dbtrans = db.Database.BeginTransaction())
{
try
{
int appId = (int)Session["ApplicationId"];
Users user = UserManager.FindById(item.Id);
db.ApplicationUsers.Add(new ApplicationUsers { ApplicationId = appId, UserId = user.Id });
db.SaveChanges();
foreach (SelectedRoles RolesItem in item.selectedRoles)
{
int roleId = db.Roles.Where(r => r.Name == RolesItem.Name).Select(r => r.Id).FirstOrDefault();
db.UserApplicationRoles.Add(new UserApplicationRoles { ApplicationId = appId, UserId = user.Id, RoleId = roleId });
db.SaveChanges();
}
dbtrans.Commit();
}
catch (Exception)
{
dbtrans.Rollback();
}
}

}
}
return RedirectToAction("UsersAddToApp");
}
ModelState.AddModelError("", "An error has occurred. Contact system administrator.");
return RedirectToAction("UsersAddToApp");
}

问题是当我选择复选框时(除了中间的第一个或最后一个,行:

foreach (SelectedRoles RolesItem in item.selectedRoles)

发送 item.selectedRoles 为空。

我怎样才能正确地做到这一点?

最佳答案

DefaultModelBinder 只会绑定(bind)集合项的索引器从零开始且连续的集合。您的问题是您正在手动创建复选框元素。由于未选中的复选框不会回发,如果您取消选中一个复选框,那么它和任何后续的复选框值将不会在您提交时绑定(bind)到集合。

接下来您尝试将复选框绑定(bind)到 string 值。复选框有 2 种状态,旨在表示一个 bool 值。

您还没有向您展示 Role( View )模型,但它应该包含一个 boolean 属性,指示它是否已被选中

public class Role
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}

然后在 View 中,使用强类型的 html 帮助程序,以便获得正确的 2 种方式模型绑定(bind)

@for (int j = 0; j < Model[i].Roles.Count; j++)
{
@Html.HiddenFor(m => m[i].Roles[j].Name) // or better use the ID property
@Html.CheckBoxFor(m => m[i].Roles[j].IsSelected)
@Html.LabelFor(m => m[i].Roles[j].IsSelected, Model[i].Roles[j].Name)
}

然后在 POST 方法中,您的集合将被正确绑定(bind),您可以使用 say 访问所选角色,

List<string> selectedRoles = model.Roles.Where(r => r.IsSelected);

请注意,您可能还想为 Role.ID(而不是 Role.Name 属性)包含一个隐藏输入,这样您就不需要执行数据库查找在您的 POST 方法中 foreach 循环。

旁注:您的发布方法需要是

public ActionResult UsersAddToApp(List<AssignUsersViewModel> model)

不是 ListAssignUsersAddModel> 模型

关于c# - 当我没有按顺序选择复选框时,POST 到 MVC Controller IEnumerable 嵌套模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30738451/

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