VAAA VAAA - 1 year ago 89
jQuery Question

Resolving Razor javascript @Url.Content prototype pattern

I have a ASP.NET MVC View (Razor) and at the end of the file I load in a section some javascript:

@section FooterScripts{

$(function () {
// creates the data table
var ajaxUrl = '@Url.Content("~/Accounting/GetListAccounts")/';

<script src="~/Scripts/pages/list-account.js"></script>


Here the variable
is resolved so the variable will get the value:
enter image description here

uses prototype pattern and has something like this:

! function($) {
"use strict";

var ListAccount = function() {
this.$window = $(window)

ListAccount.prototype.start = function() {
var $this = this;

var ajaxUrl = '@Url.Content("~/Accounting/GetListAccounts")/';

$.ListAccount = new ListAccount, $.ListAccount.Constructor = ListAccount

function($) {
"use strict";

My problem is that here the variable
doesn't get resolved. Seems like in order to
to resolve
the variable should be inside the code.

Any workaround or solution so my
prototype javascript
file gets the @Url.Content resolved?

Answer Source

if you want to use the razor in javascript, you must write the js code in the .cshtml file , as your case, you can set the ajaxUrl as a global variable and call it in your .js file, something like below:

in index.cshtml file

var ajaxUrl = '@Url.Content("~/Accounting/GetListAccounts")/';

and you can direct to use ajaxUrl in your list-account.js file now

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download