简体   繁体   中英

Create dynamic fields in asp.net mvc

I have table user with fields in additional custom fields for user that added by admin. sql click this to diagram explain this

so i want to create Register page with user fields and custom fields. i get FiledType and FieldName to list. in Controler:

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

UserField model:

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

so i want to create dynamic fields in cshtml file. 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)

For the attributes you can use a anonymouse type object with new { ... }

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

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