c# - Asp.net- Mvc Complex Model Binding -



c# - Asp.net- Mvc Complex Model Binding -

i have 2 poco class in c# , hotel , rate , 1 - many relationship in hotel create action in controller have viewbag populate drop downwards list bellow

viewbag.hotel_rate = new selectlist(db.hotel_rate, "id", "rate");

and have blow code in view populate drop downwards list

@html.dropdownlist("hotel_rate", null, new { @name = "hotel_rate.rate", @id = "hotel_rate.rate" })

every thing shoud right here , drowpdown list populate datebase , displayed in view , when post model controller model validated id of hotel rate 0 ,so entityvalidationerrors' wrong binding ? dont want utilize custome model binding class , default model binder in asp.net able handle , how?

public partial class hotel { public hotel() { } public int id { get; set; } public string name { get; set; } public virtual hotel_rate rate { get; set; } } public partial class hotel_rate { public hotel_rate() { this.hotel = new hashset<hotel>(); } public int id { get; set; } public string rate { get; set; } public string description { get; set; } public virtual icollection<hotel> hotel { get; set; } } [httppost] [validateantiforgerytoken] public actionresult create([bind(include = "id,name,hotel_rate")] hotel hotel) { if (modelstate.isvalid) { db.hotels.add(hotel); db.savechanges(); homecoming redirecttoaction("index"); }

and generated html below

<select name="hotel_rate.rate" id="hotel_rate.rate"> <option value="1">5</option> <option value="2">4</option> </select>

you have 2 issues, naming of command , utilize of [bind(include ..)] attribute since not have property named hotel_rate contains property rate (which <select name="hotel_rate.rate" ..> trying bind to).

use typed helper ensure naming issues not occur

@html.dropdownlistfor(m => m.rate.rate, (selectlist)viewbag.hotel_rate)

which render

<select name="rate.rate" id="rate_rate"> <option value="1">5</option> <option value="2">4</option> </select>

note unclear want bind to. selectlist has value id , display text rate think want m => m.rate.id otherwise binding either 1 or 2 rate property when think want bind 1 or 2 id property

your bind attribute should

public actionresult create([bind(include = "id,name,rate")] hotel hotel)

but since have included properties of hotel in include list, pointless , can deleted altogether.

c# entity-framework asp.net-mvc-4 model-view-controller

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -