Nikhil  Srivastava

Nikhil Srivastava

  • NA
  • 97
  • 10.9k

Execute Razor Code from String

Apr 26 2016 5:18 AM

Is there a way to execute text as Razor code? I am storing the HTML/JavaScript of a form in a database field. Everything works great except that I want to set values on the fields when they are pulled in and rendered in the view. For example:

<p class="form-control-static" id="requested_by">@User.Identity.GetUserName()</p>

Unfortunately, when this is pulled in and rendered, the value of the field is just the text "@User.Identity.GetUserName()" as opposed to the value returned from that method.

If you are curious as to why I am doing things this way, the form needs to be completely dynamic based on who is logging in. I have mulled over a few different solutions but this one seems to be the best. I am definitely open to some other ideas if you have them.

Here are the solutions that I was able to consider thus far:

Store field names and attributes in the database and dynamically create the form through iteration. The issue here is that some of the fields are grouped into fieldsets, some have addons, some parts require custom buttons, etc. This could definitely be done but I think it is way over-engineering and forcing a solution.

Build the form in HTML/JavaScript/Razor and store all of the field names in the database with associated user IDs. Conditionally show the fields based on whether or not the logged-in user has access to that field. Pseudo: @if(user.FormFields.Contains("field_name") ...

And the solution I am attempting now: Store all HTML/JavaScript/Razor in database as text and render with @Html.Raw(HtmlFromDatabase). As I said, this all works famously except for the Razor code which is not executing.

Any help or suggestions is much appreciated.


Answers (4)