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

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much. If i Use this approach, Can I pass data to controller on button click.
@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?
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.
I am using item variable in foreach loop. Anyhow I replaced with field but still same error.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.