简体   繁体   English

在ASP.NET MVC中创建动态字段

[英]Create dynamic fields in asp.net mvc

I have table user with fields in additional custom fields for user that added by admin. 我的表user其他自定义字段中的字段由admin添加。 sql click this to diagram explain this sql单击此处以图说明

so i want to create Register page with user fields and custom fields. 所以我想用用户字段和自定义字段创建Register页面。 i get FiledType and FieldName to list. 我得到FiledTypeFieldName列出。 in Controler: 在控制器中:

public ActionResult Index()
    {
        ViewBag.CustomeFields = userCustomeFields.GetCustomeField();
        return View();
    }

UserField model: UserField模型:

public class UserField
{
    public string FieldName;
    public string FieldTypeName;
}

so i want to create dynamic fields in cshtml file. 所以我想在cshtml文件中创建动态字段。 i wrote this code: Update: 我写了这段代码: 更新:

 @foreach (var item in ViewBag.CustomeFields)
    {
        <div class="form-group">
            @*@Html.LabelFor(i=>item.FieldTypeName  , htmlAttributes: new { @class = "control-label col-md-2" })*@
            <div class="col-md-10">
                @if (item.FieldTypeName == "Textbox")
                {
                    @Html.TextBox(item.FieldName)
                }
                </div>
            </div>
                    @*@Html.Editor(item.FieldName, new { htmlAttributes = new { @class = "form-control" } })*@
                    }

but i give error! 但我给错误! HtmlHelper<User>' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. i don't know is my way correct or not?! 我不知道我的方式正确吗?

Here again the answar to your first question, in case you want t mark it as a correct answer ^^ 如果您不想将其标记为正确答案,这里再次回答您的第一个问题^^

You have to cast it for example like this 你必须像这样铸造它

@foreach(UserField item in ViewBag.CustomFields) {

or 要么

@Html.TextBox(((UserField)item).FieldName) 

or @Html.TextBox((string)item.FieldName) 或@ Html.TextBox((string)item.FieldName)

For the attributes you can use a anonymouse type object with new { ... } 对于属性,您可以使用带有new { ... }的匿名类型对象

@Html.TextBox("nameOfTheTexbox", "initialValue", new { @class ="myCssClass myOtherCssClass", disabled = "disabled" })

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

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