27

Ok, so I'm trying to use an "if" statement within my javascript. Depending on a boolean in my model, a function should return some html or an empty string. This is basically what I want to do:

function getSomeHtml() {
var myHtml = '';
@if(Model.UseSomeNiceHtml)
{
<text> 
myHtml += '<div> <p class="label">Whatever</p></div>'; 
</text>
}
return myHtml;
}

Similar code works really well when using a foreach loop (basically replacing if with foreach in the example above). With the if statement I get the error "Encountered end tag "text" with no matching start tag. Are your start/end tags properly balanced?". When I remove the <text> tags I get the error "Too many characters in character literal".

Could anyone point me in the right direction?

Thank you! :)

4
  • 1
    What is the point of the <text> tags? It looks like the if statement just determines if the myHtml should ba altered or not. If that's the case I don't see the point of the `<text>´ tags. Commented Mar 13, 2012 at 9:15
  • 1
    When removing the <text> I get the error Too many characters in character literal. I use the <text> element in my foreach loop where it works fine. Commented Mar 13, 2012 at 9:33
  • But what purpose does it serve, the <text> tag? Commented Mar 13, 2012 at 9:35
  • @AndersDaniel see my comment on the answer below: Commented Mar 13, 2012 at 9:36

7 Answers 7

42

Ok, here's something that works for me. Tested just now.

function getSomeHtml() {
    var myHtml = '';
    @{
        if (Model.UseSomeNiceHtml)
        {
            <text> 
            myHtml += '<div> <p class="label">Whatever</p></div>'; 
            </text>
        }
    }
    return myHtml;
}

I added an extra set of {}.

Sign up to request clarification or add additional context in comments.

7 Comments

See my edit in the original question for how I solved the problem :)
I don't think you have to escape those slashes - I didn't and it worked. But in your edit you have also done what I have done in my answer, namely added {} around the C# code.
Yep, true, but it wasn't actually needed. The problem seems to be if you have for instance only closing tags on one line that the parser thing cant match up with starting tags.. Try breaking your answer up in two lines (adding to myHtml in two steps) and see :)
It is more likely that you didn't need to escape the slashes. In your edit you don't actually escape all the closing tag slashes anyway? Have you tried your own example without escaping them? Edit: I'll try that and come back to you.
I have also tried adding to myHtml in two seperate lines now, and there's no problem with that. I can add '</div>' in a line for itself and it works just fine. Also I just found out that your original code worked fine as it was (also while adding in two seperate lines). Silly of me not to have tried that first.
|
10

Ok, first: thanks for your input, it got me thinking. Eventually I found the solution and the problem was an unescaped "/" in a closing html tag. With those tags unescaped, my tags freaked out. Anyway, I figured I'd share with you what my finished code looks like. I guess it can serve as an example of how to use both C# loops and if-statements in a javascript function.

function getSubActivitiesHtml(participantId) {
var html = "";
@{
if(Model.UseSubActivities)
{
<text>
html += "<div class=\"textinput req\"><div class=\"checkbox req\">";
</text>

foreach (var subActivity in Model.SubActivities)
{
<text> 
html += "<p><input id=\"activity_" + participantId + "_@(subActivity.Id)\" name=\"Participants[" + participantId + "].SelectedSubActivities\" value=\"@(subActivity.Id)\" type=\"checkbox\" />";
html += "<label for=\"activity_" + participantId + "_@(subActivity.Id)\">@(subActivity.Name)</label></p>";
</text>
}

<text>
html += "<\/div><p class=\"label\">Delaktiviteter</p><\/div>";
</text>  
}
}

return html;
}

Notice how the closing html tags are escaped...

1 Comment

Note you can use the @: tag to indicate non-MVC code (instead of <text>...</text>). See weblogs.asp.net/scottgu/…
4

Just revisted this here many years later. Some more modern version of Razor supports this now:

    @if (Model.isValid)
{
       @: console.log("This statement will be printed.");
}

This only prints one statement, so if you had to do multiple you would have to add more lines of @:

But then you can use it to call a function defined elsewhere

Comments

1

try to remove the <text> tags or put them inside the myHtml += ''; statement

5 Comments

I'd say remove them, they are of no use.
dunno what his html and css is, he might use the <text> tag for something, that's why both remove or move :)
I think the <text> thing is used to tell the Razor parser to treat anything in between the tags as text...
@ErikKinding Correct. Your "Too many characters in character literal" error when you remove the <text> tag is because it's trying to parse the myHtml += line as C#. In C# 'x' is a char, which can only be a single char. So you're right to include the <text> tag.
See my edit in the original question for how I solved the problem :)
1

This works too.

function getSomeHtml() {
    var myHtml = '';
    if('@Model.UseSomeNiceHtml' === '@true')
    {
         myHtml += '<div> <p class="label">Whatever</p></div>'; 
    }
    return myHtml;
}

Comments

1
function  @(treeviewConfig.AddNewTreeviewNode)(treeNode) {
        @if (!string.IsNullOrEmpty(NodeIDKey) && !string.IsNullOrEmpty(treeviewConfig.ParentIdExpr)) {
            <text>
                treeNode['@(treeviewConfig.ParentIdExpr)'] = treeNode['@(NodeIDKey)'];
                treeNode['@(NodeIDKey)'] = 0;
        </text>
        }
        @if ( !string.IsNullOrEmpty(treeviewConfig.DisplayExpr)) {
               <text>
            treeNode['@(treeviewConfig.DisplayExpr)'] =  'nue';
         </text>
        }

        @if ( !string.IsNullOrEmpty(treeviewConfig.EditTreeviewNode)) {
             <text>
             treeNode['@(treeviewConfig.EditTreeviewNode)'] = 'nue';
         </text>

        }

        PopulateTreeViewNodeInputs(treeNode);
       @(treeviewConfig.ShowTreeEditPopup)();
    }

This worked for me quite well

Comments

0

Try this:

  function getSomeHtml() {
    @{
      var myHtml = "";
      if(Model.UseSomeNiceHtml)
      {
        myHtml += "<div> <p class='label'>Whatever</p></div>";
      }
    }
    return "@myHtml";
  }

1 Comment

See my edit in the original question for how I solved the problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.