0

I am trying to have a column in my database where the string stored is:

'"Test count:" + @mycontroller.count()'

And then in my cshtml file do

<li>@Html.Raw(@MenuItem.ItemText)</li>

However, all I am getting displayed is the string in the database and not it the actual result from the controller count() function. How do I get that string to render/execute?

  • You want to execute some code in the string to be executed ? – Shyju Aug 09 '16 at 17:58
  • I want the @mycontroller.count() function that is within a string in a database to be called when I bring it in within the CSHTML file. So instead of displaying ""Test count:" + @mycontroller.count()", it displays "Test Count: 5". – Patrick Aug 09 '16 at 18:02
  • Do you really need to execute arbitrary code from the database, or can you live with a relatively short list of variables to substitute? – 15ee8f99-57ff-4f92-890c-b56153 Aug 09 '16 at 18:05
  • I thought about doing the substitution option but would prefer to execute the arbitrary code. – Patrick Aug 09 '16 at 18:06

2 Answers2

0

You cannot call a function in a Controller from a view since you don't have an instance of such controller on you view. There are 2 ways of doing what you want:

  • Having an action on your Controller that given the string you want to use returns the data you require and make an AJAX call to get it

  • Calculate the data you want before you render the View and pass it in along your model, either using ViewBag|ViewData or as part of your View Model

Luiso
  • 4,173
  • 2
  • 37
  • 60
0

If understand your intention correctly, you are trying to store C# code in the database and then execute it in your view. That will not (by default) work, since C# is statically compiled language, which means that each change to your code needs to be first compiled to binary code before the code can be executed.

The same applies to MVC razor syntax views (cshtml files) - when a cshtml file is first requested, it is compiled to binary code and then executed.

If you are certain about what you want to do however, there perhaps may be a way, as described in this SO post. But I would first recommend you to describe exactly what it is you are trying to achieve that you ended up with this question.

Community
  • 1
  • 1
davke
  • 350
  • 1
  • 7