简体   繁体   中英

Url.Content for javascript

I currently use this approach to obtain the correct relative URI (independent of the deployment situation). Razor code (asp.net mvc 3):

@section JavaScript
{  
    <script type="text/javascript">
        var _getUrl =  "@Url.Content("~/bla/di/bla")";
    </script>
}

Separate js file:

$.ajax({
    url: _getUrl,

Do you reckon there is a better approach?

Personally I prefer using HTML5 data-* attributes or including the URL as part of some DOM element that I unobtrusively AJAXify.

The thing is that you never write $.ajax calls flying around like that. You write them to correspond to some DOM events. Like for example clicking of an anchor. In this case it's trivial, you just use an HTML helper to generate this anchor:

@Html.ActionLink("click me", "someAction", "somecontroller", new { id = "123" }, new { @class = "link" })

and then:

$('.link').click(function() {
    $.ajax({
        url: this.href,
        type: 'GET',
        success: function(result) {
            ...
        }

    });
    return false;
});

or maybe you are AJAXifying a form:

@using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" }))
{
    ...
}

and then:

$('#myForm').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function(result) {
            ...
        }
    });
    return false;
});

Another example would be to use HTML5 data-* attributes when an appropriate url is not available on the corresponding DOM element. Suppose that you want to invoke a controller action with AJAX when the selection of a dropdown changes. Think for example cascading ddls.

Here's how your dropdown might look like:

@Html.DropDownListFor(x => x.SelectedValue, Model.Values, new { id = "myDdl", data_url = Url.Action("SomeAction") })

and then:

$('#myDdl').change(function() {
    var url = $(this).data('url');
    var selectedValue =  $(this).val();
    $.getJSON(url, { id: selectedValue }, function(result) {
        ...
    });
});

So as you can see you don't really need this _getUrl global javascript variable that you declared in your view.

I would do the following:

Razor C# script before Javascript

@{
    var myUrlString = Url.Action("ActionName", new { controller="ControllerName" });
}

JavaScript

$.ajax('@myUrlString',{
    // options
});

You could also use Url.RouteUrl or Url.HttpRouteUrl .

EDIT - showing example with separated JS file

Razor

@{
    var myServerGeneratedValue = Url.Action("ActionName", new{controller="ControllerName"});
}
<script type="text/javascript">
    var myHelperObject = new MyHelperObject();
    myHelperObject.Init('@myServerGeneratedValue');
</script>

JS file

var MyHelperObject = function(){

    this.Init = function(serverGeneratedValue){
        // do something with serverGeneratedValue
    };

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM