Setting ajax url for jQuery in JS file using ASP.NET MVC

前端 未结 5 1520
星月不相逢
星月不相逢 2020-12-12 16:43

When doing a Ajax call to an MVC action currently I have my javascript inside the View, not inside its own JS file.

It is then very easy to do this:

         


        
5条回答
  •  孤城傲影
    2020-12-12 17:13

    Here's another way:

    In your master page, include an area for inline scripts:

    
      ...
      
      ...
    
    

    Then in the Page_Load, create a utility function:

    protected void Page_Load( object sender, EventArgs e )
    {
      AddInlineScript( string.Format( "$.url=function(url){{return '{0}'+url;}}", GetBaseUri() ) );
      ...
    }
    
    private Uri GetBaseUri()
    {
      var requestUrl = Request.Url.AbsoluteUri;
      var i = requestUrl.IndexOf( request.Path );
    
      return new Uri( requestUrl.Substring( 0, i ) );
    }
    
    private void AddInlineScript( string content )
    {
      var script = new HtmlGenericControl( "script" );
    
      script.Attributes.Add( "type", "text/javascript" );
      script.InnerHtml = content;
    
      _inlineScripts.Controls.Add( script );
    }
    

    Now you can use this function in your ajax:

    $.ajax({
      url: $.url('path/to/my-handler'),
      ...
    });
    

提交回复
热议问题