Mehmet Eren Yener
Mehmet Eren Yener

Reputation: 2036

Razor with Javascript

 @if (Model.PaymentMethodTypeId == (int) PaymentMethodType.PayPal)
 {
     var url = @MyLibraryHtml.JavascriptEncodeUrl(Url.RewriteAction("SaveNewPaymentMethod", "PaymentMethods"));
     var args = form.serialize();
     @Html.Raw(" var url = ")
 }

Inside if block the code is Javascript, but as I expected, Razor see var url and var arg as .NET variable.

I know I can use Html.Raw but is there any other better solution for this problem, Because I believe that Html.Raw breaks readibility

Upvotes: 1

Views: 85

Answers (2)

SLaks
SLaks

Reputation: 888223

You need to wrap the contents of the block in <text> tags to force Razor to treat it as markup rather than server-side code.

However, writing server-generated Javascript code is generally a bad idea; it's rather unreadable and is very easy to make XSS holes.

Instead, you should store the server-side code in data- attributes, and read them in normal JS code.

Upvotes: 1

nemesv
nemesv

Reputation: 139808

You can use the <text></text> element to tell Razor that the code inside the if should be treated as "text" instead of c# code:

@if (Model.PaymentMethodTypeId == (int) PaymentMethodType.PayPal)
 {
     <text>
     var url = @MyLibraryHtml.JavascriptEncodeUrl(Url.RewriteAction("SaveNewPaymentMethod", "PaymentMethods"));
     var args = form.serialize();
     </text>
 }

Alternatively if you only have a few lines you can use the @: to "escape" single lines:

@if (Model.PaymentMethodTypeId == (int) PaymentMethodType.PayPal)
 {
     @:var url = @MyLibraryHtml.JavascriptEncodeUrl(Url.RewriteAction("SaveNewPaymentMethod", "PaymentMethods"));
     @:var args = form.serialize();
 }

Upvotes: 1

Related Questions