asp.net mvc - Generate list in view and pass it to controller -
i'm writing hotel reservation web site asp.net , mvc 4. have class named reservation have list of contacts. in create view want dynamically create contacts. (number of contacts = adults + kids , determined in create reservation view) how post contact information controller?
public partial class reservation { public int id { get; set; } public int roomtype_id { get; set; } public system.datetime fromdate { get; set; } public system.datetime todate { get; set; } public byte adults { get; set; } public byte kids { get; set; } public decimal price { get; set; } public int user_id { get; set; } public int state_id { get; set; } public virtual reservationstate reservationstate { get; set; } public virtual roomtype roomtype { get; set; } public virtual user user { get; set; } public virtual icollection<transaction> transactions { get; set; } public virtual icollection<contact> contacts { get; set; } }
should set maximum number contacts(for example 5 , write this?
[httppost] public actionresult create(reservation reservation,contact adult1,contact adult2, contact adult3, contact adult4, contact adult5, contact kid1,contact kid2, contact kid3) { if(reservation.adults>0) reservation.contacts.add(adult1); if(reservation.adults>1) reservation.contacts.add(adult2); ... if (modelstate.isvalid) { _db.reservations.add(reservation); _db.savechanges(); return redirecttoaction("index"); } }
it's dirty there better way? can pass list of contacts?
@for (var = 0; < model.contacts.count(); i++) { @html.editorfor(m => m.contacts[i]) }
the thing need instantiate list of new contacts. why view model preferable in constructor based upon value on view model:
public class reservationviewmodel { public reservationviewmodel() { contacts = new list<contact>(); (var = 0; < adults + kids; i++) { contacts.add(new contact()); } } ... }
alternatively, after see code gets generated you'll understand how modelbinder expects receive data back. inputs like:
<input id="contacts_0__name" name="contacts[0].name" />
where 0
iteration count of contacts. if simulate structure manually, modelbinder pick data well.
Comments
Post a Comment