如果我禁用使用或条件,输入复选框不会将其模型值传递给控制器

Input checkbox not passing its Model Value to the controller if I make disabled using or condition

我已经给出了使复选框有条件地禁用的代码,但是当我调用 post 方法时,总是将值作为 null 而不是其模型值传递。禁用

后如何将模型值传递给post方法

我的代码

input type="checkbox" disabled="@(isdisabled || isDofDisabled ? "disabled" : null)" asp-for="@Model.attendanceLogList[i].IsDayOffMarked"  />

您需要 post 的“名称”属性。我建议不要使用标准 HTML 标签:

 @Html.CheckBoxFor(m => m.isDofDisabled)

always the value being passed as null rather than its model value

对于复杂类型的每个 属性,模型绑定会在源中查找名称模式 prefix.property_name。如果什么都没有找到,它只查找没有前缀的 property_name 。您的前端名称类似于:attendanceLogList[index].IsDayOffMarked。所以接收数据可能如下所示:

 [HttpPost]
 public IActionResult Index(List<Attendance> attendanceLogList)
 {
    return View();
 }

或使用父模型:

[HttpPost]
public IActionResult Index(Test Test)
{
    return View();
}

我的测试模型设计:

public class Test
{
    public List<Attendance> attendanceLogList { get; set; }
}
public class Attendance
{
    public bool IsDayOffMarked { get; set; }
}

How can I pass model value to post method after disabled

浏览器默认不支持禁用属性submit with forms

要解决此问题,您可以设置隐藏输入来存储值:

@model Test

<form method="post">
    @for (int i = 0; i < Model.attendanceLogList.Count(); i++)
    {
        if(isdisabled||isDofDisabled)
        {
            <input hidden asp-for="@Model.attendanceLogList[i].IsDayOffMarked" />
        }
        <input type="checkbox"
               disabled="@(isdisabled || isDofDisabled ? "disabled" : null)"
               asp-for="@Model.attendanceLogList[i].IsDayOffMarked" />
    }
    <input type="submit" value="Post" />
</form>

注:

不知道你的详细后端代码是多少,如果还是收到空值,尝试在参数前加[FromForm]指定来源:

public IActionResult Index([FromForm]List<Attendance> attendanceLogList)

或:

public IActionResult Index([FromForm]Test Test)