1

I'm new to ASP.NET MVC. After reading many different examples I still can't get this done.

I have some JS scripts bundled and one out of the bundle (because I'm using a different main script per page)

(_Layout.cshtml)

@Scripts.Render("~/bundles/modernizr")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/datatables")
@RenderSection("scripts", required: false)

And in my view

(index.cshtml)

@section Scripts
{
    <script src="@Url.Content("~/Scripts/index.js")"></script>
}

In javascript code I am trying to call a specific URL of my application

(index.js)

$('#table').DataTable({
    ajax: '@Url.Action("List", "Documents")'
});

Of course in my application a controller is definend with the name DocumentsController and with a List method, returning the correct JSON.

Still it seems no-one is ever replacing my url

enter image description here

If I include my index.js in the bundle, nothing changes. Where is the mistake? Who and when is replacing that URL?

Thank you

1
  • please show your controller code. Commented Mar 15, 2020 at 11:26

1 Answer 1

0

You can't use Razor code inside a *.js file because they're served directly as static files and aren't processed by ASP.NET (nor *.ts files because they're transpiled to *.js at build-time).

What you can do instead is to render Razor-generated JavaScript in your View/Page and have your TypeScript or JavaScript expect that data to be available.

Like so:

Index.cshtml

<script type="text/javascript">
var scriptUrls = {
    listDocuments: '@Url.Action("List", "Documents")';
};
</script>

Index.ts (if using TypeScript)

interface PageUrls {
    readonly listDocuments: string;
};

declare var scriptUrls: PageUrls;

//

$('#table').DataTable({
    ajax: scriptUrls.listDocuments
});

Index.js

$('#table').DataTable({
    ajax: scriptUrls.listDocuments
});
Sign up to request clarification or add additional context in comments.

3 Comments

I think you're wrong, look here : link
@AmirNorouzpour The link you pointed to is for a <script> element inside a .cshtml file. Whereas my answer for this question is for when the script is inside a separate *.js file.
Ok, now it's clear. I did assume that code was in js file. thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.