简体   繁体   中英

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

I have this 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; }
}

In 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>
}

In database I have saved SkillId . On the basis of skillId , how to get checkbox selected when editing?

Since you are performing loop list of Skills and want to pre select one skill.So what you can do is set the attribute to selected if the value of SkillId within the loop is equal to the SkillId in the Model

@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>

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM