开发者

Moving Url.Action into Jquery/JS? (MVC Web App)

Environment: ASP.NET 3.5, MV开发者_运维知识库C 2 Web App, in the View file Index.aspx

I have the following jqGrid (excerpt of code):

    $("#list").jqGrid({
        url: '<%= Url.Action("GridData") %>',
        datatype: 'json',

This is in an inline JS function called populateGrid. I need to move this function out of the View and into its own JS. In order to do this I need to store the <%= Url.Action("GridData") %> as a variable in javascript.

This:

var griddata = <%= Url.Action("GridData") %>;

doesn't appear to work. I am wondering what syntax I should use and/or how I can do this. The populateGrid function is going to be called by multiple pages so that is why it is being put into a .js file.


Throw in some quotes:

var griddata = '<%= Url.Action("GridData") %>';

Should solve your specific problem there.


The problem your having is that the griddata variable is local to the $(document).ready closure. you need to decleare it outside that scope to be global or pass it to the js scope. So to make it global you would do:

var griddata = ... // this outside the function/closure

$(document).ready(function() {});

Now, polluting the global namespace with all your config variables may not be the best method to pass this type of data around.... you could create a config object to hold all you config vars (with defaults and all) in your master page, so it gets correctly initialized for every page... something like:

var myAppConfig = {
   gridData : '<%= Url.Action("xxxx") %>',
   otherConfig : 'some more configuration here'
};

then you can use it in your js files

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜