ASP.NET MVC CheckBoxList from model with List Property

前端 未结 4 1448
没有蜡笔的小新
没有蜡笔的小新 2020-12-08 07:01

Apologies if the title is unclear.

I\'m trying to return my model from a form submit in ASP.NET MVC.

My question is nearly the same as this question, only di

相关标签:
4条回答
  • 2020-12-08 07:33

    Post a list of check boxes to server and get list of checked items
    linq left join to check whether checked, generating checkboxes,received checked list

    View

        List<eDurar.Models.tbl_ISOCetificate> ModList = db.tbl_ISOCetificate.ToList();
    
        var li = (from cert in db.tbl_ISOCetificate join comCert in db.tbl_CompCertificate on cert.Cert_id equals comCert.CompCer_id into jo from b in jo.DefaultIfEmpty()
                  select new {cert.Cert_id,cert.Cert_Name,chkd = b.CompCer_SerId==null?"":"checked"}).ToList();
    
    
        foreach (var item in li)
        {       
            @:<div style="width: 30%;  display: inline-block; margin: 1em">
            @:<input type="checkbox" @item.chkd name="CheckedCertificates" value="@item.Cert_id">
            @:<label>@item.Cert_Name</label>
            @:</div> 
        }
    

    Controller

      [HttpPost]
        public ActionResult ManageSurveyGroup(int[] CheckedCertificates)
        {
            return View();
        }
    
    0 讨论(0)
  • 2020-12-08 07:37

    From your code in the view, the post should work fine providing your post action looks like this:

    [HttpPost]
    public ActionResult Action(Model model)
    {
        return View(model);
    }
    

    i.e. passing your model across as the argument.

    Also make sure you have your model reference in the view too:

    @model YourNameSpace.Model
    
    0 讨论(0)
  • 2020-12-08 07:39

    No need to go away from Razor at all.

    This works for me:

    for (var i = 0; i < Model.UserRoles.Count(); i++)
    {
        var role = Model.UserRoles[i];
        @Html.HiddenFor(model => model.UserRoles[i].RoleId)
        @Html.CheckBoxFor(model => model.UserRoles[i].Selected)
        @Html.LabelFor(model=> model.UserRoles[i].Name, role.Name)
    }
    
    0 讨论(0)
  • 2020-12-08 07:46

    See below code, this way you don't need to hide the role Id, also when you save the selected roles for the user, you don't need to loop through all roles to see which role is selected.

    View

    @foreach (Roles info in Model.UserRoles)
    {
        <span>
            <input type="checkbox" class="checkbox" name="selectedRoles" value="@info.RoleName" id="@infoRoleName" />
            <label for="@info.RoleName">@info.RoleName</label>
        </span>
    }
    

    Action

    [HttpPost]
    public ActionResult CreateUsers(Model model, string[] selectedRoles)
    {
           //
    }
    
    0 讨论(0)
提交回复
热议问题