VAAA VAAA - 19 days ago 8
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{

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

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

}


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

Now,
list-account.js
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")/';

},
//init
$.ListAccount = new ListAccount, $.ListAccount.Constructor = ListAccount
}(window.jQuery),

//initializing
function($) {
"use strict";
$.ListAccount.start();
}(window.jQuery);


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


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

Answer

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

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

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

Comments