ASP.NET MVC, including ASP in Javascript

Is it possible to put ASp.NET tags in my javascript, which is in a separate script file. For example, I have the following

 $.getJSON("/Postcode/GetAddressResults/" + $get("SearchPostcode").value, null, function(data) {

which I want to include, but it does not look like ASP tags!

var action = "<%=Url.Content('~/Postcode/GetAddressResults/')%>" + $get("SearchPostcode").value
        $.getJSON(action, null, function(data) {

However, this does not work, what am I doing wrong?

+3
source share
3 answers

Add a meta tag to your home page (s) to save the value of the current application path from the host (bit ~ represents).

In your Javascript, create a function that will resolve the prefix path using the contents of the meta tag.

Edit

Example on request: -

Put this code in the chapter section of the main pages: -

  <meta id="meta.AppDomainAppVirtualPath"
    name="AppDomainAppVirtualPath" value="<%=HttpRuntime.AppDomainAppVirtualPath%>" />

Your javascript has this feature enabled: -

function resolveUrl(url)
{
    if (url.charAt(0) == "~")
    {
        if (!resolveUrl.appPath)
        {
           var meta = document.getElementById('meta.AppDomainAppVirtualPath');
           resolveUrl.appPath = meta ? meta .getAttribute("content") : '/';
        }

        if (resolveUrl.appPath == '/')
            return url.slice(1, url.length;
        else
            return resolveUrl.appPath + url.slice(1, url.length);
    }
    else
    {
        return url;
    }
}

Now your line of code: -

$.getJSON(resolveUrl("~/Postcode/GetAddressResults/") + $get("SearchPostcode").value, null, function(data) {
+1

JavaScript script, ASP.NET, . ASP.NET.

0

No, you can’t. You can open the path in your javascript view, but not directly to your external javascript file.

@David M Attaching all of this is not really necessary, you can embed the dynamic part and leave the other part hard-coded.

Regards, Peter

0
source

Source: https://habr.com/ru/post/1705575/


All Articles