0

I am trying to bind the Checkboxlist with some data from an API in MVC but after checking unchecking the check boxes am posting the form to get checked options from the list but in Post action am getting the Model as null.

I am passing List<ListItem> to View from Get action and receiving as IEnumerable<ListItem> in view and In post action am receiving as IEnumerable<ListItem>.

I tried to change the param to List and FormCollection only in case of FormCollection i can able to recieve model as resultsView.

How can i get the model in Post action of the controller?

Model

public class ListItemModel
    {
        public int Id
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public bool Checked
        {
            get;
            set;
        }  
    }

EditorTemplate

@model APITestCore.Models.ListItemModel

@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
@Html.CheckBoxFor(x => x.Checked)
@Html.DisplayFor(x => x.Name)

View

@model IEnumerable<APITestCore.Models.ListItemModel> 

@{
    ViewBag.Title = "ListTest";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>List</h2>

@using (Html.BeginForm())
{
    @Html.EditorForModel()

    <input id="Submit1" type="submit" value="submit" />

}

Controller Action // POST:

[HttpPost]
    public string DeviceList(IEnumerable<ListItemModel> list)
    {
        string response = String.Empty;
        foreach(ListItemModel item in list)
        {
            if (item.Checked)
            {
                response += item.Id;
                response += ",";
            }
        }
        return response;
    }
user3625533
  • 339
  • 1
  • 4
  • 20
  • tried it before posting the question. it does not solved the problem. – user3625533 Mar 09 '17 at 21:42
  • Of course it does! Read the dupe carefully. You need to create an `EditorTemplate` for your model –  Mar 09 '17 at 22:20
  • Tried using the Editor template but no luck where i am going wrong? – user3625533 Mar 09 '17 at 22:59
  • How would I know what mistakes you have made - I cant see your code and I'm not psychic :) Ask a new question showing the code you have tried and indicating what is not working and I will correct it for you. –  Mar 09 '17 at 23:01
  • Thanks for your time! @Muecke. Found the problem. EditorTemplate must have the same name as Model Class. I named my model as ListItemModel and created a EditorTemplate as ListItem. After renaming the EditorTemplate to ListItemModel it started working as expected. – user3625533 Mar 09 '17 at 23:24
  • I suspect you have that the wrong way around since the code in the question shows you model is named `ListItem` (not `ListItemModel`), but glad to see you worked it out :) –  Mar 09 '17 at 23:28

0 Answers0