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

烂漫一生 提交于 2019-12-08 10:13:39

问题


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
    }

回答1:


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....


来源:https://stackoverflow.com/questions/5600289/dynamically-rendering-and-posting-form-elements-in-asp-net-mvc-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!