Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • wolulcmit 357 posts 693 karma points
    Nov 06, 2011 @ 07:07
    wolulcmit
    0

    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:

    @* 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
    }

    but have it named so it can be reused.

    @renderform{
     my form here
    }

    thanks for any pointers!

    - Tim

  • wolulcmit 357 posts 693 karma points
    Nov 06, 2011 @ 08:04
    wolulcmit
    1

    ah hah!

    @RenderPage did the damage for me.

    as in separating that code out to a different file and the using renderpage:

    @RenderPage("QuestionForm.cshtml")
  • Ben Norman 167 posts 276 karma points
    Nov 06, 2011 @ 10:21
    Ben Norman
    0

    cool

    BTW, thanks for posting the answer

  • Owen 123 posts 246 karma points
    Nov 06, 2011 @ 14:18
    Owen
    1

    how about @helper?

    @helper renderform(){

    your form here

    }

  • Sebastiaan Janssen 5058 posts 15520 karma points MVP admin hq
    Nov 06, 2011 @ 15:49
    Sebastiaan Janssen
    1

    @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)).

Please Sign in or register to post replies

Write your reply to:

Draft