Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor @helper functions not rendering any Html

I have a model with an object property, and a value type id number, and want to create a different editor control depending on the value type number.

I'm trying to use @help razor contructs, however none of the contents of the helpers are rendered to the page.

@helper noEditor()
{
    <div>noEditor</div>
}
@helper stringEditor()
{
    <div>stringEditor</div>
}
@helper intEditor()
{
    <div>intEditor</div>
}
@helper boolEditor()
{
    <div>boolEditor</div>
}
@helper collectionEditor()
{
    <div>collectionEditor</div>
}

@switch(Model.ValueTypeId)
{
    case 1: stringEditor(); break;
    case 2: intEditor(); break;
    case 3: boolEditor(); break;
    case 4: collectionEditor(); break;
    default: noEditor(); break;
}

When I put a break point on the @switch I can see the debugger move to the correct helper, but it skips immediately to the end of the function then exits the switch, nothing is rendered.

Any idea on what I'm doing wrong here?

like image 356
asawyer Avatar asked Jul 30 '13 14:07

asawyer


1 Answers

To render text with Razor you have to use the @ sign. If you change your code to

@switch(Model.ValueTypeId)
{
    case 1: @stringEditor() break;
    case 2: @intEditor() break;
    case 3: @boolEditor() break;
    case 4: @collectionEditor() break;
    default: @noEditor() break;
}

it should work.

Alternative you can use Response.Write like this:

@switch(Model.ValueTypeId)
{
    case 1: Response.Write(stringEditor()); break;
    case 2: Response.Write(intEditor()); break;
    case 3: Response.Write(boolEditor()); break;
    case 4: Response.Write(collectionEditor()); break;
    default: Response.Write(noEditor()); break;
}

which is basically what the @ does in razor.

like image 164
Mattias Jakobsson Avatar answered Oct 23 '22 02:10

Mattias Jakobsson