Search code examples
asp.net-mvc-3checkboxwebgrid

MVC3 WebGrid CheckBox


I'm trying to add a checkbox to a column on a web grid, and I'm finding it hard using Html.CheckBox to get it to render. If I use input type="checkbox" it renders, but I can't seem to save the value in the view model.

I have a rather complex view, which has two webGrids, and you select items in one to move to the other, when moved to grid1, you can check a box against each of the rows if you want. Everything is working, except I can't get the value of the checkbox to save.

The code for my grid that has the checkbox looks like this:

var grid1 = new WebGrid(source: Model.FieldsInTemplate, canSort: false, defaultSort:"FieldName");

    @grid1.GetHtml(headerStyle:"gridGroupRow", tableStyle: "gridGroup", rowStyle: "gridRow", alternatingRowStyle: "gridRowAlt", columns: grid1.Columns(
        grid1.Column("FieldName", "Field Name"),
        grid1.Column(header: "Required", format: @<text><input name="IsRequired" type="checkbox" value="@item.IsRequired" /></text>),
        grid1.Column(format: (item) => new HtmlString("<a href='#' id='test' onclick='updateTemplate(false," + item.FieldId.ToString() + ");'>Remove</a>"))
             ))

So using the above, the grid renders with a checkbox, but on submission the entity is always false. The view uses a viewModel of:

public class TemplateFieldInteractViewModel
{
    public IList<MetadataTemplateFieldInstanceDisplayViewModel> FieldsInTemplate
    {
        get;
        set;
    }

    public IList<MetadataTemplateFieldInstanceDisplayViewModel> FieldsNotInTemplate
    {
        get;
        set;
    }
}

The MetadataTemplateFieldInstanceDisplayViewModel looks like:

public class MetadataTemplateFieldInstanceDisplayViewModel
{
    public int FieldId {get;set;}

    public string FieldName {get;set;}

    public bool IsRequired {get;set;}
}

Please let me know if this is a little vague, I'm new here, and don't want to overload you with too much unnecessary code.

Cheers

Mark


Solution

  • The value of a checkbox does not determine if it's "checked" or not. You'll need to use checked="checked".

    I'm not 100% learned with Razor, but here's an attempt:

    <input name="IsRequired" type="checkbox" @if(item.IsRequired) { <text>checked="checked"</text>} value="@item.IsRequired" /> 
    

    Does this solve your problem?