在asp.net mvc4中动态创建控件

时间:2014-09-15 08:00:55

标签: c# asp.net-mvc-4

我正在尝试在asp.net mvc4中动态创建控件但是有一些问题并且还需要一些建议。下面的语句不起作用,它显示了“row.Options”下面的错误行                                @for(var.in row.Options)

除此之外,我可以动态创建下拉列表或下拉列表,如果是,那么我如何根据当前场景分配名称和值?

查看                 

            @foreach(var row in Model.Controls) {
                var i = 0;
                <div>                        
                     <label>@row.Caption</label>
                     @if (row.ControlType == "text") {
                        <input type="text" name="@row.Name" />
                     } else if (row.ControlType == "select") {

                        <select name="@row.Name">
                            @for (var o in row.Options ) {
                                <option value="@o.Value>">@o.Text</option>
                            }
                        </select>                             
                     }                                          
                </div>  
                i++;
            }
            </ul>

查看模型

public List<SelectListItem> MembershipTypeList { get; set; }

public class Controls
{
    public string Caption {get; set;}
    public string ControlType {get; set;} 
    public string Name {get; set;}
    public List<SelectListItem> Options { get; set; }
}

控制器代码段

    public ActionResult Signup()
    {
        signup.MembershipTypeList.Add(new SelectListItem()
        {
            Text = "Student  £18.00",
            Value = "Student"
        });

        signup.MembershipTypeList.Add(new SelectListItem()
        {
            Text = "Associate  £18.00",
            Value = "Associate"
        });

        signup.Controls = new List<Controls>();
        signup.Controls.Add(new Controls() { Caption = "Age", ControlType = "text", Name = "txtage" });
        signup.Controls.Add(new Controls() { Caption = "Name", ControlType = "text", Name = "txtname" });
        signup.Controls.Add(new Controls() { Caption = "Membership", ControlType = "select", Name = "txtmembership", Options = signup.MembershipTypeList });

        return View("Signup", signup);
}

2 个答案:

答案 0 :(得分:2)

我认为它可能只是一个额外的角括号导致这种情况,请尝试更改为:

<option value="@o.Value">@o.Text</option>

答案 1 :(得分:1)

首先,您的代码无效:

<select name="@row.Name">
    @for (var o in row.Options ) {
        <option value="@o.Value>">@o.Text</option>
    }
</select> 

删除&#34; >&#34;来自@o.Value>

渲染,因为它打破了html。

修正:

<select name="@row.Name">
    @foreach (var o in row.Options ) {
        <option value="@o.Value">@o.Text</option>
    }
</select>