how do you reuse chunks of code in razor? I have the following where I'm checking if a post has been made, and displaying a message and rendering the same form if the question was answered incorrectly:
@* If user posts and has answered the question correctly*@ @if (IsPost && Request["question"]==Request["correctanswer"]) { <p>yay! you picked the right answer!</p>
@* If user posts and answers the question incorrectly*@ }else if(IsPost && Request["question"]!=Request["correctanswer"]){ <p>got that wrong? try again sucker...</p> -- render form here --
@* If user hasnt even posted yet*@ } else{
-- render the same form here -- }
so how do I call a block of code in multiple places? so that I dont have to maintain two bits of code that are the same
I've looked into using @functions but it looks hellishly complicated for me (too c-sharpy)
what I want to do is use a codeblock like: @{ my form here }
@helper works as well indeed, if you have some pure code call (something you would've previously done in an xslt extension), then you have two options: stick it in the app_code folder (your filename will be your namespace, example: Helpers.cs with a method of CamelCase(string text) will be called like this: @Helpers.CamelCase("my string")) or put it in a seperate project and refer to the methods like you normally would (@MyHelpersProject.CamelCase("my striing)).
Reusing Code blocks in Razor?
how do you reuse chunks of code in razor?
I have the following where I'm checking if a post has been made, and displaying a message and rendering the same form if the question was answered incorrectly:
so how do I call a block of code in multiple places? so that I dont have to maintain two bits of code that are the same
I've looked into using @functions but it looks hellishly complicated for me (too c-sharpy)
what I want to do is use a codeblock like:
@{
my form here
}
but have it named so it can be reused.
@renderform{
my form here
}
thanks for any pointers!
- Tim
ah hah!
@RenderPage did the damage for me.
as in separating that code out to a different file and the using renderpage:
cool
BTW, thanks for posting the answer
how about @helper?
@helper renderform(){
your form here
}
@helper works as well indeed, if you have some pure code call (something you would've previously done in an xslt extension), then you have two options: stick it in the app_code folder (your filename will be your namespace, example: Helpers.cs with a method of CamelCase(string text) will be called like this: @Helpers.CamelCase("my string")) or put it in a seperate project and refer to the methods like you normally would (@MyHelpersProject.CamelCase("my striing)).
is working on a reply...