简体   繁体   中英

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

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();
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM