user472269
user472269

Reputation: 367

Building dynamic view based on Fields returned from DataBase in Asp.Net MVC3

I want to render view at runtime based on fields returned from Database. Any help should be appreciated, for designing the prototype / approach

I have below model,

public class DynamicFields
{
    public string propertyName { get; set; }
    public string propertyType { get; set; }
} 

In Controller, it will be List<DynamicFields>

So based on propertyType, i have to render the control like TextBox/DateTime

Upvotes: 1

Views: 1369

Answers (1)

Yoeri
Yoeri

Reputation: 2249

You could create EditorTemplates for every value of propertyType

_textInput.cshtml (assuming textInput is a possible value of propertyType)

@model DynamicFields
@Html.TextBoxFor(item => Model.propertyName)

_dateTimeInput.cshtml (assuming dateTimeInput is a possible value of propertyType)

@model DynamicFields
@Html.TextBoxFor(item => Model.propertyName, new {class = "datetime"})

the view:

@model IEnumerable<DynamicFields>

@foreach(var field in Model){
    @Html.LabelFor(model => field.propertyName)
    @Html.EditorFor(model => field.propertyName, field.propertyType) @*tell razor which template to use *@

}

more information can be found here: http://msdn.microsoft.com/en-us/library/ee407414(v=vs.118).aspx

updated my answer considering the foreach loop with knowledge from this answer: https://stackoverflow.com/a/1987585/690178

Upvotes: 1

Related Questions