Using TypeScript with an inline server-side `<script>` block and ASP.Net

依然范特西╮ 提交于 2019-12-03 10:28:50

The short answer is no.

You could write a TypeScript file and paste the compiled JavaScript in, but that's as close as you'll get. One practical problem would be that if the compiler transformed your TypeScript into JavaScript, you would lose your TypeScript code. This is why you have a TypeScript file and a JavaScript file.

What's the compelling reason to put the script inline rather than referencing an external script - maybe there is another solution to your problem that doesn't require inline scripts?

You could create a server-control that compiles the code at runtime, and caches it:

[DefaultProperty("Text")]  
[ToolboxData("<{0}:TypeScript runat=server></{0}:TypeScript>")]  
public class TypeScript : WebControl  
{  
    public string Text { get; set; }

    protected override void RenderContents(HtmlTextWriter output)  
    {  
        output.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");  
        if (!string.IsNullOrEmpty(this.ID))
        {
            output.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);  
        }
        output.RenderBeginTag("script");
        output.Write(CompileToJavaScript(Text));
        output.RenderEndTag();
    }

    private string CompileToJavaScript(string typeScript)
    {
        // TODO: Call tsc with the code, and return the result.
    }
} 

You might be able to compile tsc.js with JScript.NET, if you care to implement the IO-layer, and weed out some JScript.Net (not JavaScript) syntax errors.

  • have a work around for it, what I do is declare the variables needed from razor in a script tag

    <script type="text/javascript">
    
    //Razor variables initialized here and declared in the TypescriptFile.ts file
    
    var url = "@Url.Action("NewRequest", "Request")";
    
    </script>
    
  • next declare the url variable in the Typescript file

    //TypescriptFile.ts
    declare var url: string;
    alert(url);
    
  • use it

  • sad to see that Visual Studio 2013 still does not provide server side support.

Although it's not a real solution to your problem, but why don't you leave your TypeScript code as is in <script type="text/typescript"> and use Typescript Compile to have it compiled at runtime?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!