1

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
user472269
  • 367
  • 1
  • 4
  • 19

1 Answers1

1

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

Community
  • 1
  • 1
Yoeri
  • 2,249
  • 18
  • 33
  • Thank you very much. If i Use this approach, Can I pass data to controller on button click. – user472269 Apr 21 '14 at 21:59
  • @Html.LabelFor(item => item.propertyName) Does not contain definition for "PropertyType" and no extension method for PropertyType accepting first argument. Can you please help me on this error? – user472269 Apr 21 '14 at 22:02
  • in my code 'field' is correct, not item (see the foreach loop: '@foreach(var field in Model){' ) and yes, passing data to a controller is called submitting a form. – Yoeri Apr 21 '14 at 22:06
  • I am using item variable in foreach loop. Anyhow I replaced with field but still same error. – user472269 Apr 21 '14 at 22:10
  • C# is case-sensitive. propertyType != PropertyType. Please don't use the comments to ask new questions. Comments don't show up in search results. I corrected my answer btw. Please excuse me for other minor mistakes. This is written out of the blue and it is 12.15am where I live :'). The code should point you in the right direction though. – Yoeri Apr 21 '14 at 22:19