jeudi 5 novembre 2015

CheckboxList MVC EditorFor Template PostBack

I inherited some incomplete code. The developer was using an editorfor template for creating his checkboxlist. The problem is that it does not bind back to the model so that I can get the data back to the server side. Anyone have an example on how to use an editorfortemplate for a checkboxlist and send data back bound to the model? Below is the editortemplate content.

EDITOR TEMPLATE called ServiceTypeViewModel.cshtml

     @model List<ViewModels.ServiceTypeViewModel>
<table>

@{int k = 0; int columns = 2;}

@for (int i = 0; i < (Model.Count / columns + (Model.Count % columns == 0 ? 0 : 1)); i++)
{
    <tr>
    @for(int j = 0; j<columns; j++){
        <td>
            @if (k<Model.Count) { 
                <input name="ProvidedServices[@(k)].Name" id="ProvidedServices__@(k)__Name" type="hidden" value="@Model[k].Name">       
                <input name="ProvidedServices[@(k)].Selected" class="CB" id="ProvidedServices__@(k)__Selected" type="checkbox" value="true">
                <input name="ProvidedServices[@(k)].Selected" type="hidden" value="false">
                <input name="ProvidedServices[@(k)].ServiceTypeClass" id="ProvidedServices__@(k)__ServiceTypeClass" type="hidden" value="@Model[k].ServiceTypeClass">       
                <input name="ProvidedServices[@(k)].ServiceType" id="ProvidedServices__@(k)__ServiceType" type="hidden" value="@Model[k].ServiceType">       
                @Html.DisplayFor(m=>Model[k].Name)
                k++;
            }
        </td>
    }
    </tr>
}
</table>

MODEL BELOW

  public class ServiceTypeViewModel
    {
        public string ServiceTypeClass { get; set; }
        public string ServiceType { get; set; }
        public bool Selected { get; set; }
        public string Name { get { return ServiceTypeClass + " " + ServiceType; } }
    }
}

EditorFor Template Definition in main Model.

[UIHint("ServiceTypeViewModel")]
public List<ServiceTypeViewModel> ProvidedServices { get; set; }

Index.cshtml

    @Html.LabelFor(x => x.ProvidedServices)
    @Html.EditorFor(x => x.ProvidedServices) 

Aucun commentaire:

Enregistrer un commentaire