Bob Horn
Bob Horn

Reputation: 34297

Mixing Razor and JavaScript

I'm trying to use an anchor tag within a webgrid to call a javascript function. I can't get the syntax right. This is as close as I've come:

gridSpecs.Column(header: "", columnName: "", format: (item) => @:<a href="javascript:void(0);" onclick="DoSomeWork(@item.EquipmentId);">x</a>),

However, the VS IDE still complains about a missing parenthesis. I've tried wrapping the anchor tag with <text></text>. I've also tried it without the a: and with the a: (above).

How am I supposed to be able to use an anchor to call my javascript method?

I've even tried Html.ActionLink(), but that makes a call to the server, and I don't want to do that:

@Html.ActionLink("x", null, new { id = item.Id }, new { onlick = "DoSomeWork();" })

If it helps, here is the entire webgrid HTML:

<div class="webgrid-wrapper">
    <div id="grid">
        @gridSpecs.GetHtml(
            tableStyle: "webgrid",
            headerStyle: "webgrid-header",
            footerStyle: "webgrid-footer",
            alternatingRowStyle: "webgrid-alternating-rows",
            columns: gridSpecs.Columns(
                gridSpecs.Column(header: "", columnName: "", format: (item) => @:<a href="javascript:void(0);" onclick="DoSomeWork(@item.EquipmentId);">x</a>),
                gridSpecs.Column("Equipment.EquipmentId", "ID"),
                gridSpecs.Column("Equipment.Name", "Name"),
                gridSpecs.Column("Equipment.LegacyEquipmentId", "Legacy ID")))
    </div>
</div>

This is the line that finally worked:

(Hope this helps save someone else two hours...)

gridSpecs.Column(header: "", columnName: "",
    format: (spec) => MvcHtmlString.Create(string.Format("<a href='' onclick='DoSomeWork({0}); return false;'>x</a>", spec.Equipment.EquipmentId))),

Upvotes: 1

Views: 1528

Answers (1)

James McCormack
James McCormack

Reputation: 9944

Suspect the line should be:

gridSpecs.Column(header: "", columnName: "", format: (item) => string.Format("<a href=\"\" onclick=\"DoSomeWork({0}); return false;\">x</a>", item.EquipmentId)),

Your approach didn't work because the line is .net code, and already in razor context. You only use @: or <text> to break out of Razor context (i.e. write out the rest of the line to the Response), which isn't appropriate here.

Sorry for tinkering with your logic but I consider it best practise to use string.Format for string interpolation, and to avoid the use of javascript in href attributes.

UPDATE v2 (v1 was no good :)

I've not used WebGrid so I didn't realize that it escapes HTML sent to the format property. Can you try this:

gridSpecs.Column(header: "", columnName: "", format: (item) => MvcHtmlString.Create(string.Format("<a href=\"\" onclick=\"DoSomeWork({0}); return false;\">x</a>", item.EquipmentId))),

Upvotes: 1

Related Questions