Erik Kinding
Erik Kinding

Reputation: 1870

C# if statement within Javascript, Razor/MVC3

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! :)

Upvotes: 27

Views: 51530

Answers (7)

Danielh
Danielh

Reputation: 213

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

Upvotes: 4

mutuma
mutuma

Reputation: 31

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

Upvotes: 1

RayLoveless
RayLoveless

Reputation: 21038

This works too.

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

Upvotes: 1

Erik Kinding
Erik Kinding

Reputation: 1870

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

Upvotes: 10

Zaid Masud
Zaid Masud

Reputation: 13443

Try this:

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

Upvotes: 0

AndersDaniel
AndersDaniel

Reputation: 1162

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 {}.

Upvotes: 42

trembon
trembon

Reputation: 768

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

Upvotes: 1

Related Questions