簡體   English   中英

如何從數據庫中獲取 ASP.NET MVC 中選中的復選框?

[英]How to get checkbox selected in ASP.NET MVC from database?

我有這個 model

public class UserModel
{
   public List<UserModel> Skills { get; set; }
   public int SkillId { get; set; }
   public string SkillName { get; set; }
   public bool IsSelected{ get; set; }
}

在 Edit.cshtml 中

@for (var i = 0; i < Model.Skills.Count; i++)
{
            <div>
                @Html.HiddenFor(x => x.Skills[i].SkillId)
                @Html.CheckBoxFor(x => x.Skills[i].IsSelected, new { htmlAttributes = new { @class = "form-control } })
                @Html.DisplayFor(x => x.Skills[i].SkillName, new { htmlAttributes = new { @class = "form-control" } })
            </div>
}

在數據庫中,我保存了SkillId skillId的基礎上,如何在編輯時選擇復選框?

由於您正在執行技能的循環列表並且想要預先 select 一項技能。因此,如果循環中的 SkillId 的值等於 Model 中的 SkillId,您可以將屬性設置為選中

@for (var i = 0; i < Model.Skills.Count; i++)
{
        <div>
            @Html.HiddenFor(x => x.Skills[i].SkillId)
            @Html.CheckBoxFor(x => (x.Skills[i].SkillId==Model.SkillId), new { htmlAttributes = new { @class = "form-control" } })
            @Html.DisplayFor(x => x.Skills[i].SkillName, new { htmlAttributes = new { @class = "form-control" } })
        </div>

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM