【问题标题】:Checkbox input always return false value复选框输入总是返回假值
【发布时间】:2018-11-16 13:28:30
【问题描述】:

我正在使用 asp.net core 2.1,我有一个简单的视图,其形式如下:

@model Security.WebUi.Pages.AssignClaimToUserModel

<form method="post">
    <div>
        <label>User:  </label>
        <select asp-for="UserId" asp-items="@Model.UserList">
            <option>Please select one</option>
        </select>
    </div>
    <div>
        <label>Role?</label>
        <input type="checkbox" name="IsRole" id="isRole" />
    </div>
    <div>
        <label>Claim Type</label>
        <input type="text" name="ClaimType" id="claimType" />
    </div>
    <div>
        <label>Claim Value</label>
        <input type="text" name="ClaimValue" />
    </div>
    <button type="submit">Submit</button>
</form>

如您所见,我有一个带有 IsRole 属性的复选框

所以在我的模型中我有一个布尔值:

 public class ClaimToUserdModel
    {
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }
        public Guid UserId { get; set; }
        public bool IsRole { get; set; }
    }

然后在我调用的方法中:

public async Task<IActionResult> OnPost(ClaimToUserdModel model)
            {
              ....
            }

但它总是抛出错误,它不关心是否选中。我做错了什么?

【问题讨论】:

  • 默认情况下,bool 为 false,除非您在代码中的某处将其设置为 true。

标签: c# asp.net asp.net-core asp.net-core-2.1


【解决方案1】:

我遇到了同样的问题,我通过编写 html 复选框标记来修复它,将其命名为与属性名称相同的名称,并且 value = true,如果未选中复选框,则无需担心,因为它不会被提交,在你的情况下就是这样

<input type="checkbox" name="Remember" value="true" checked="@Model.YourmodelPropertyname"/>

您还使用 jquery 设置复选框选中的属性值。

【讨论】:

    【解决方案2】:

    你可以试试:

    <input type="checkbox" name="IsRole" id="isRole" value="true" />
    

    您似乎正在使用 ASP.NET Core Razor 页面,您也可以参考以下示例:

    @page
    @model razorpages.Pages.AssignClaimToUserModel
    @{
        ViewData["Title"] = "AssignClaimToUser";
    }
    
    <form method="post">
    
    <div>
        <label>Role?</label>      
        <input asp-for="ClaimToUserdModel.IsRole" name="IsRole">
    </div>
    
    <button type="submit">Submit</button>
    

    后面的代码:

    public class AssignClaimToUserModel : PageModel
    {
        public ClaimToUserdModel ClaimToUserdModel;
        public void OnGet()
        {
    
        }
    
        public async Task<IActionResult> OnPost(ClaimToUserdModel model)
        {
            return null;
        }
    }
    
    public class ClaimToUserdModel
    {
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }
        public Guid UserId { get; set; }
        public bool IsRole { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 1970-01-01
      • 2013-10-29
      • 2016-05-03
      • 2012-12-26
      • 2015-12-01
      • 2021-08-24
      相关资源
      最近更新 更多