1

I created viewmodel including list, this list is for checkbox in view. But when I click submit, I get all data of viewmodel except this list. This list is keep getting null. Here my code example,

public class viewmodel
{
    public int Id{get;set;}
    public string Name{get;set;}
    public list<Occupation> occupationList{get;set;}
}

public class Occupation
{
    public int Id{get;set;}
    public string Name{get;set;}
    public bool IsSelected{get;set;}
}

Inside view,

  @model project.viewmodel
  @using (Html.BeginForm())
  {

   @Html.AntiForgeryToken()

    <div class="form-horizontal">

    <div class="form-group">
        @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-4">
            @Html.TextBoxFor(model => model.Id, new Dictionary<string, object> { { "class", "form-control ui-widget" }, { "readonly", "readonly" } })
            @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-4">
            @Html.TextBoxFor(model => model.Name, new Dictionary<string, object> { { "class", "form-control ui-widget" }, { "readonly", "readonly" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2">Occupation</label>
        <div class="col-md-4">
            @if (Model.occupationList != null)
            {
                foreach (var z in Model.occupationList)
                {
                    @Html.HiddenFor(z => z.Id)
                    @Html.HiddenFor(z => z.Name)
                    @Html.CheckBoxFor(z => z.IsSelected)
                    @Html.DisplayFor(z => z.Name)
                }
            }
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-success" />
        </div>
    </div>

when I click submit, inside conroller I got only occupationList is null, other data can get. Can someone explain for my error. I am totally new about mvc. Thank you guys.

Alice
  • 111
  • 1
  • 10

0 Answers0