c# - List property inside a model is coming null while posting the model to controller -


i creating basic mvc3 application in trying post complex model type list property (of model type) controller. when so, property coming null inside model.

i have model follows:

public class employeelist {     public list<employee> employeelist { get; set; } } 

and employee again model :

public class employee {     public int id { get; set; }     public string name { get; set; } } 

controller code is:

[httpget] public actionresult index() {     employeelist em = new employeelist();     em.employeelist = new list<employee>() { new employee(){}};     return view(em); }  [httppost] public actionresult index([bind(prefix = "employeelist")]employeelist employeelist1) {     ....... } 

and views follows:

index.cshtml:-

@model test.models.employeelist @{     viewbag.title = "index";  }  <h2>index</h2>  @using (html.beginform("index", "home", formmethod.post, new { @id = "testform" })) {     @html.labelfor(m => m.eid)     @html.editorfor(m => m.eid)     @html.hiddenfor(m => m.eid)     <br />     @html.editorfor(x => x.employeelist)     <br />     <p>         <input type="submit" value="post" />     </p> } 

and editor template view is:

@model test.models.employee  @html.labelfor(model => model.id) @html.textboxfor(model => model.id) @html.hiddenfor(model => model.id) <br /> <br /> @html.labelfor(model => model.name) @html.textboxfor(model => model.name) @html.hiddenfor(model => model.name) 

on browser checked , names , id's generated follows:

name="employeelist[0].id", id="employeelist_0__id"  name="employeelist[0].name", id="employeelist_0__name" 

but when post employeelist model controller, employeelist null.

please me if missing something. in advance.

i think mvc model binding might getting confused. try changing name of model's property employeelist listofemployees. e.g.

public class employeelist {     public list<employee> listofemployees { get; set; } }  [httppost] public actionresult index([bind(prefix = "listofemployees")]employeelist employeelist1) {     ....... }  @model test.models.employeelist @{     viewbag.title = "index";  }  <h2>index</h2>  @using (html.beginform("index", "home", formmethod.post, new { @id = "testform" })) {     @html.labelfor(m => m.eid)     @html.editorfor(m => m.eid)     @html.hiddenfor(m => m.eid)     <br />     @html.editorfor(x => x.listofemployees)     <br />     <p>         <input type="submit" value="post" />     </p> } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -