简体   繁体   中英

How can I use the helper I created in WebMatrix (C# Razor syntax)?

I am trying to use WebMatrix to create static html. (Think CMS.)

I have this helper in App_Code/CardHelpers.cshtml

@helper Cards (string mysuit){

// Class Tags
var ss = Html.Raw("<span class = \"spade\">"); 
var sh = Html.Raw("<span class = \"heart\">");  
var se = Html.Raw("</span>");

// Suits
var S = Html.Raw(ss + "&spades;" + se); 
var H = Html.Raw(sh + "&hearts;" + se);

<p> @mysuit and @H</p>

}

I call it with

@CardHelpers.Cards("S")

The static html output is

<p> S and <span class = "heart">&hearts;</span></p>

So I can use @H inside the helper to create the html I want, but how can I pass in a suit (such as "S") and create the appropriate html. Here, I just get back the S, but what I want to return is

<span class = "spade">&spades;</span>

The whole point of Razor is that you can mix markup and C# syntax. So what you want to do is put a conditional or switch statement in that selects the correct output for the given input, like this:

@{ 
  string result = "";
  switch(mysuit) { 
    case "H": result = H; break;
    case "S": result = S; break;
    default: break;
  }
  <p> @mysuit and @result</p>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM