matt weston
matt weston

Reputation: 63

How to display Razor helper code that is inside a variable?

We are trying to build a form dynamically using code that is stored in the database. Depending upon what controls we want for a particular form, we put them in a List and pass them to our view.

Inside the view we run through the list outputing the code for each; however, when I do the following

foreach(var control in Model.ParameterControls)
{
     @control.code
}

I just get the code output in "" which prints the code itself to screen instead of rendering the control. How do I take a control such as @Html.Textbox("title") or @Html.DevExpress().TextBox("Title") and get it to render from a variable?

Edit

ParameterControls is defined as follows

    List<ControlModel> ParameterControls

Where ControlModel is:

    public string Title { get; set; }
    public string ControlName { get; set; }
    public ParameterType Type { get; set; }
    /* additional irrelevant properties removed */

And ParameterType is:

    public int TypeID { get; set; }
    public string TypeName { get; set; }
    public string TypeCode { get; set; }

TypeCode is defined as the control (ie)

     @Html.DevExpress().TextBox("Test").GetHtml()

Upvotes: 3

Views: 191

Answers (2)

ramiramilu
ramiramilu

Reputation: 17182

I take a control such as @Html.Textbox("title") or @Html.DevExpress().TextBox("Title") and get it to render from a variable?

If you want to Parse Razor String in a varialbe to browser displayable Html and finally display it on a view, then use RazorEngine.

Sample Code of Razor Engine parsing -

  Razor.SetTemplateBase(typeof(HtmlTemplateBase<>));

  string template = 
  @"<html>
      <head>
        <title>Hello @Model.Name</title>
      </head>
      <body>
        Email: @Html.TextBoxFor(m => m.Email)
      </body>
    </html>";

  var model = new PageModel { Name = "World", Email = "[email protected]" };
  string result = Razor.Parse(template, model);

Upvotes: 0

erikkallen
erikkallen

Reputation: 34391

foreach(var control in Model.ParameterControls)
{
    <text>@control.code</text>
}

Upvotes: 1

Related Questions