简体   繁体   English

动态呈现和发布ASP.NET MVC 2中的表单元素

[英]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. 使用JavaScript将选定房间数的新输入元素插入DOM。 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....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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