简体   繁体   中英

dynamically rendering and posting form elements in ASP.NET MVC 2

I have to render a set of form elements dynamically (based on value selected in some other form element) and post their values back to controller. I have a search form for Hotel Industry which captures hotel related search parameters such as No of Rooms, No of Adults, No of Children, Ages of Children etc.

Based on the value selected for “No of Rooms” dropdown, I have to render/show form elements to capture No of Adults, No of Children & Ages of Children FOR EACH ROOM. What would be a better way to dynamically render and carry values for above form elements (No of Adults, No of Children & Ages of Children fields FOR EACH ROOM) from my View to Controller?

My VIEW MODEL looks something like this:

public class HotelSearchView
{
    public DateTime CheckInDate { get; set; }
    public DateTime CheckOutDate { get; set; }
    public string DestinationCity { get; set; }

    public List<GuestView> Guests { get; set; }

    // Other fields...
}

public class GuestView
    {
        public string RoomNumber { get; set; }
        public string GuestType { get; set; } // Adult, Child etc.
        public string GuestAge { get; set; } // Will contain a value ONLY for GuestType:Child
    }

Use JavaScript to insert new input elements into your DOM for the number of rooms selected. Each set of inputs should have the right name so that it get bound to the list in your view model correctly:

<input type="text" name="Guests[0].RoomNumber" />
<input type="text" name="Guests[0].GuestType" />
<input type="text" name="Guests[0].GuestAge" />

<input type="text" name="Guests[1].RoomNumber" />
<input type="text" name="Guests[1].GuestType" />
<input type="text" name="Guests[1].GuestAge" />

etc....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM