开发者

Better solution to using Url.Action in javascript code

开发者 https://www.devze.com 2023-02-06 22:22 出处:网络
In my current project using asp.net MVC 3 (using razor), when I\'m making Ajax calls, I have to keep the JS on the view page because I want to use Url.Action to generate the URL. This means I can\'t s

In my current project using asp.net MVC 3 (using razor), when I'm making Ajax calls, I have to keep the JS on the view page because I want to use Url.Action to generate the URL. This means I can't split the js code ou开发者_JAVA技巧t into .JS files, Is there a better solution than what I'm currently doing.


I tend to accomplish this in a similar way as above, with a slightly different twist as I like namespacing my javascript.

The javascript file looks something like:

var my = {};

my.viewname = 
{
   init : function(settings){
      // do some work here. settings.someImportantUrl has my json/ajax url eg.
      alert(settings.someImportantUrl );
   }
}

Then my view would contain something like:

<script language='javascript'>
  // allocate an object with variables you want to use in the external js file
  var settings = {someImportantUrl: '<%=Url.Action(...)%>'};
  // call an init method for the current view
  my.viewname.init(settings);
</script>


You can define only urls in view and keep all other javascript code in .js files.

There is code from view in my MVC.NET 1 application:

<script type="text/javascript" src="<%=Url.Content("~/Scripts/Account/ManageUsers.js")%>"></script>

<script type="text/javascript" src="<%=Url.Content("~/Scripts/Account/ManageUsersAndGroups.js")%>"></script>

<script type="text/javascript">

    var getUsersUrl = '<%= Url.Action("GetUsers", "Account") %>';
    var getUserDetailsURL = '<%= Url.Action("GetUserDetails", "Account") %>';

    <%If Not ViewData("readOnly") Then%>
    var changeRolePermissionsUrl = '<%= Url.Action("ChangeRolePermissions", "Account") %>';
    var deleteUserUrl = '<%= Url.Action("DeleteUser", "Account") %>';
    var resetPasswordUrl = '<%= Url.Action("ResetPassword", "Account") %>';
    var updateUserGroupsUrl = '<%= Url.Action("UpdateUserGroups", "Account") %>';
    var updateUserDetailsUrl = '<%= Url.Action("UpdateUserDetails", "Account") %>';
    <%End If%>  
</script>

So, you can even don't render urls for actions which cannot be invoked by user because of security reasons. (ViewData("readOnly") means user have read only access to screen).

And there is a part of code in js file:

function GetUsersList() {
    ajax.getJSON(getUsersUrl, {}, function(data) {
        if (data != false) {
            ShowUsers(data);
        }
        else {
            jAlert('Error during users list retrieving.');
        }
    });
}

Where getUsersUrl is defined in View


your javascript code should be reside in separate javascript file. you can use global variables to link your view and javascript. E.g. view page looks like below.

view html ...
<script type="text/javascript">
var pageUrl = @GetURL()
</script>

<script type="text/javascript" src="/js/script.js"/>

script.js file use the pageUrl variable and other global variables.


I'm not sure of security ramifications on this, but another way to do it would be to use the @Url.Action to set the 'id' of the html markup, then you can create a javascript click function, like the following:

View

<div class="someClickable" id='@Url.Action("Action", "Controller")'>
</div>

Referenced javascript file

$(function() {
    $('someClickable').click(function () {
        $.ajax({
            url: this.id,
            success: someJSFunction,
            dataType: "html"
        });
    });
});

You end up with the desired url stored in the 'id' of the 'div'. This seems to be a reasonable solution as long as you are doing read only actions.

0

精彩评论

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