![](/img/trans.png)
[英]Passing a String value through asp-for=“…” into a Model in ASP.Net core isn't working the way it should
[英]How to use asp-for and conditional if in a checkbox using asp.net core?
我正在尝试在复选框中使用条件 if 和 asp-for 属性,但如果我同时使用它们中的一个则不起作用。 我想检查选定的选项,我需要 asp-for 来更新我的列表。 这是我的代码:
@{
ViewData["Title"] = "EditRole";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
var i = 0;
}
<div class="col-lg-6">
@foreach (var all in Model.ActionAndControllerNames)
{
foreach (var selected in Model.SelectedActionAndControllerNames)
{
#region ToUpper selected
var action = all.ActionName.ToUpper();
var controller = all.ControllerName.ToUpper();
var area = "";
if (all.AreaName != null)
{
area = all.AreaName.ToUpper();
}
#endregion
<div class="form-group">
@{
var check = selected.AreaName == area &&
selected.ControllerName == controller && selected.ActionName ==
action?"checked":"";
}
<input type="checkbox" @((selected.AreaName == area &&
selected.ControllerName == controller && selected.ActionName
== action)?"checked":"") asp-
for="ActionAndControllerNames[i].IsSelected"/>
<input type="hidden" readonly="readonly" asp-
for="ActionAndControllerNames[i].ActionName" />
<input type="hidden" readonly="readonly" asp-
for="ActionAndControllerNames[i].ControllerName" />
<input type="hidden" readonly="readonly" asp-
for="ActionAndControllerNames[i].AreaName" />
<label for="@all.IsSelected">
@(Model.ActionAndControllerNames[i].AreaName ?? "NoArea") -
@Model.ActionAndControllerNames[i].ControllerName -
@Model.ActionAndControllerNames[i].ActionName
</label>
</div>
i++;
}
}
</div>
当我使用它时,只有条件 if 有效,而 asp-for 无效,当我一起改变它们的位置时,它给了我条件 if 的错误。 我尝试了 https://stackoverflow.com/a/54559960/13604077方式,但它也没有工作。 我应该怎么办? 编辑这是 model:
public class EditRoleViewModel
{
public EditRoleViewModel()
{
ActionAndControllerNames = new List<ActionAndControllerName>();
}
[Required()]
public string RoleName { get; set; }
public string RoleId { get; set; }
public IList<ActionAndControllerName> ActionAndControllerNames { get;
set; }
public IList<ActionAndControllerName> SelectedActionAndControllerNames {
get; set; }
}
这是 ActionAndControllerName class:
public class ActionAndControllerName
{
public string AreaName { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }
public bool IsSelected { get; set; }
}
我想编辑选定的复选框,所以我需要显示哪个复选框被选中,所以我需要一个 if 条件来比较所有复选框与选定的复选框。我还需要在 controller 中获取新的选定复选框列表,所以我需要 asp-为了。
标签助手不允许在元素的属性或标签声明区域中出现 C#。所以你做的事情是不可能的。
你可以像下面这样使用checked="@check"
:
<input type="checkbox" asp-for="ActionAndControllerNames[i].IsSelected" checked="@check" />
但是在您的情况下,您只能进行如下更改:
@if (selected.AreaName == area &&
selected.ControllerName == controller && selected.ActionName ==
action)
{
<input type="checkbox" asp-for="ActionAndControllerNames[i].IsSelected" checked />
}
else
{
<input type="checkbox" asp-for="ActionAndControllerNames[i].IsSelected" />
}
参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.