Home > Software engineering >  Asp.Net MVC view how to add script src from backend?
Asp.Net MVC view how to add script src from backend?

Time:11-12

I have a MVC view where I am using Yandex external API for address search.

This is the script I have to add in order to use the Yandex services.

<script src="https://api-maps.yandex.ru/2.1/?apikey=xxxxxxxxxx&lang=ru_RU" type="text/javascript">

Is there a way to read this script src from the backend instead of directly using it in the View, as it contains the api key?

CodePudding user response:

You can use a server side method to 'read' the script src file from the ASP.Net server. You would perform an HTTP GET using something like System.Net.Http.HttpClient. This is effective if you are retrieving JSON data or some other type of data to process on the server.

However, the C# backend would not process JavaScript instructions. For that you would need a server side JavaScript engine such as Node, or the client's web browser.

Including the JavaScript file in the View will allow the client's JavaScript engine to handle processing. But as you have implied, nothing in the View is hidden from the client.

CodePudding user response:

You can create an Action that loads and returns the script, then reference that Action in your html, eg:

<script src='@Url.Action("LoadYandex")'>

and

public ActionResult LoadYandex() {
    // HttpClient to get the file
    return Content(file, "text/javascript");
}
  • Related