c# - MVC - Binding ICollection property -
i using mvc , ef db first. models created ef. in model have 2 icollection type properties.
my problem when post form, properties empty (i'm not sending them view emty)
my model:
public partial class business relationship { public account() { this.account_level = new hashset<account_level>(); this.account_team = new hashset<account_team>(); } public long id { get; set; } public string username { get; set; } public string password { get; set; } public bool isadmin { get; set; } public virtual icollection<account_level> account_level { get; set; } public virtual icollection<account_team> account_team { get; set; } }
note: icollection properties not nowadays in view, need them in controller.
edit:
i have added below code view. in html, can see icollection values added hidden when create post icollection properties still empty. still not getting values back.
for (int = 0; < model.account_level.count(); i++) { @html.hiddenfor(m => m.account_level.elementat(i).accountid) @html.hiddenfor(m => m.account_level.elementat(i).id) @html.hiddenfor(m => m.account_level.elementat(i).levelid) } (int = 0; < model.account_team.count(); i++) { @html.hiddenfor(m => m.account_team.elementat(i).accountid) @html.hiddenfor(m => m.account_team.elementat(i).id) @html.hiddenfor(m => m.account_team.elementat(i).teamid) }
the problem code defaultmodelbinder
not able bind hidden fields model, because your hidden fields not next right naming convention.
the hiddenfor method in razor view generates like:
<input id="accountid" type="hidden" value="1" name="accountid" data-val-required="the accountid field required." data-val-number="the field accountid must number." data-val="true">
as see generated name accountid
not right if want create bindable.
the right name must account_level[0].accountid
.
here total illustration of right naming hidden fields:
for (int = 0; < model.account_level.count(); i++) { @html.hiddenfor(m => m.account_level.elementat(i).accountid, new { @name = string.format("account_level[{0}].accountid", i) }) @html.hiddenfor(m => m.account_level.elementat(i).id, new { @name = string.format("account_level[{0}].id", i) }) @html.hiddenfor(m => m.account_level.elementat(i).levelid, new { @name = string.format("account_level[{0}].levelid", i) }) }
this create sure hidden fields names recognized default model binder.
here can find more info asp.net mvc naming conventions:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
c# asp.net-mvc
No comments:
Post a Comment