jeudi 15 janvier 2015

c# mvc reusable checkbox partial

I have a partial view that uses a list (CheckBoxListModel) of classes (CheckBoxModel) with a string and bool to create a list of checkboxes. The code works to create the checkboxes and sends the selected ones back to the controller when the page posts. I am trying to find a way to make my partial reusable. As you can see in the code I send the partial the full Model and this works to get the updated checkboxes when the page posts. I tried to send my Model's CheckBoxListModel, but it does not work because when it creates the checkboxes the name is incorrect. I would like to reuse the partial by sending it a CheckBoxListModel so I do not have to create a separate partial every time I need a set of checkboxes.


I tried to change_CheckBoxListPartial.cshtml to





@model MySite.Models.ViewModels.CheckBoxListModel
...
@Html.EditorFor(x => x.CheckBoxes)
...



but without the clmReturnOptions the checkbox names end up as name="CheckBoxes[0].isChecked" instead of name="clmReturnOptions.CheckBoxes[0].isChecked" so they are not updated in the Model when the page posts and gets back to the controller.


I have been looking at: http://ift.tt/1kzycwr but still can't seem to get the checkboxes to work without sending the entire model to my partial.


Thanks in advance.





CheckBoxListModel.cs
public class CheckBoxListModel
{
public IList<CheckBoxModel> CheckBoxes { get; set; }

public CheckBoxListModel()
{
}
}

public class CheckBoxModel
{
public string CheckBoxName { get; set; }
public bool isChecked { get; set; }

public CheckBoxModel()
{ }

public CheckBoxModel(string name, bool ischecked)
{
CheckBoxName = name;
isChecked = ischecked;
}
}


ReportFilterViewModel.cs
public class ReportFilterViewModel
{
public ReportFilterViewModel()
{
clmReturnOptions = new CheckBoxListModel();
}

public CheckBoxListModel clmReturnOptions { get; set; }
}



_CheckBoxListPartial.cshtml
@model MySite.Areas.Reports.Models.ViewModels.ReportFilterViewModel

@{
Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<title>Returns Options</title>
</head>
<body>
<div class="col-md-4">
<!-- COLUMN 1 -->
<div class="outline mtm">
<div class="row mlm mrm">
<h6>Returns Options</h6>
</div>
@Html.EditorFor(x => x.clmReturnOptions.CheckBoxes)
</div>
</div>
</body>
</html>


CheckBoxModel.cshtml
@model MySite.Models.ViewModels.CheckBoxModel

<div class="row mlm mrm">
<div class="form-group">
<label class="checkbox">
@Html.CheckBoxFor(x => x.isChecked, new { @data_toggle = "checkbox" })
@Html.LabelFor(x => x.CheckBoxName, Model.CheckBoxName)
@Html.HiddenFor(x => x.CheckBoxName)
</label>
</div>
</div>






Aucun commentaire:

Enregistrer un commentaire