天道酬勤,学无止境

What the best way to handle server side tags inside of a js file?

I'm using Asp.NET MVC and have a huge dependency on JQuery throughout my entire application (not sure if that's important here or not). I'm trying to build a set of js library files to go along side my views. The problem that I'm faced with is that I need a way to manage the server side location of my files and action links for all of my image maps and ajax calls.

For now, I'm stuck putting all of my scripting code inside each aspx pages so that I can use the server side scripting tags like this:

    $("#StartDate").datepicker({
        changeMonth: true,
        changeYear: true,
        showOn: 'button',
        buttonImage: '<%= Url.Content("~/Content") %>/Images/calendar.png',
        buttonImageOnly: true
    });

and

    function fillDates(periodType, periodOffset)
    {
      $.ajax({
        url: '<%= Url.Action("GetDates", "Tracking") %>',
        dataType: "json",
        data: {"pt": periodType, "po": periodOffset},
        success: function(result){
            if (result.Status == "Success")
            {
                $("#StartDate").val(result.StartDate);
                $("#EndDate").val(result.EndDate);
            }
            else
            {
                alert(result.Status + ": " + result.Message);
            }
        }
      });        
    }

I'd like to move this code to a js file. How would I do this and still be able to map to the root directory of my application.

评论

You can put the base url in your view, and reference it from your js files

// site.master
var appPath = <%=ResolveUrl("~/")%>;

// *.js
function dosomething()
{ 
    var src = appPath + "content/images/test.png";
    var action = appPath + "controller/action";
}

Note: this method requires that you write your action urls manually instead of calling Url.Action().

Though I've never tried it, you could map .js files to the ASP.NET handler and process them when they are served. How you do that mapping depends on the version of IIS and you'd probably use an HTTPModule to do the processing.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐