How to use content containing razor markup as a parameter for a method?

What I'm trying to do is write javascript mixed with markup and methods containing a razor in a .cshtml file and send it to a separate method for use later.

My .cshtml looks something like this:

@{SomeClass.SaveForLater(@<script type="text/javascript">window.alert('@Model.SomeParamter')}</script>); 

And inside the SomeClass class:

 public static void SaveForLater(HtmlString str) { // will be using str.ToString() here and save the string output for use later on. } 

But I get an error message:
CS1660: Unable to convert lambda expression to enter "System.Web.HtmlString" because it is not a delegate type

Am I using the wrong type of argument or do I need to rethink the whole concept?

Solution Thanks to the SLaks below, I ended this:

 public static void SaveForLater<T>(Func<T, HelperResult> template, dynamic model) { // template(model).ToHtmlString() } 

Using it as follows:

  @{SomeClass.SaveForLater<SomeModel>( @<script type="text/javascript">window.alert('@Model.SomeParamter')</script>, Model ); 
+4
source share
1 answer

You are trying to use the built-in helper .
You should accept Func<Something, HelperResult> .

+2
source

Source: https://habr.com/ru/post/1382100/


All Articles