Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

c# - building relative URLs for an MVC app with JavaScript

I'm having trouble getting C# and JavaScript/jQuery to play nice here.

I have a knockout view model, plain old javascript object... one of its property/methods fires off an .ajax() call, and the url parameter is built using some of its other property values (javascript variables).

This works fine when completely contained in JavaScript, but when deployed as an app to IIS, the relative pathing is hosed.

In MVC3 normally I would use something like @Url.Action and let the server side build the address... but again, the trick is C# is unaware of the changing javascript values.

Code:

var viewModel = {
    vendors: ko.observableArray([]),
    count: ko.observable(10),
    page: ko.observable(1),
    filterText: ko.observable(""),
    submit: function () {
        $.ajax({
            // works fine, until deploy when it is no longer a site relative URL
            url: 'vendors/' + viewModel.count() + '/' + viewModel.filterText(),

            // does not work, because C# is unaware of the javascript variables.
            //url: @Url.Action("Vendors", "Home", new { count = viewModel.count(), filter = viewModel.filterText() })

            dataType: 'json',
            success: function (data) {
                viewModel.vendors(data);
            }
        });    
    }
    // next: // load sequence starting with (page+1 * count) 
    // previous: // load sequence starting with (page-1 * count)
};
ko.applyBindings(viewModel);

Question:

My question then is, how can I build the url for the ajax call using the javascript variable values (ex. count, filterText) and still map from the relative root of the application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way we do this in my MVC 3 project is to include the following in the Master Layout:

<script type="text/javascript">
    var baseSiteURL = '@Url.Content("~/")';
</script>

Then you just prepend that to your URLs in the JavaScript.

Which in your sample would read:

url: baseSiteURL + 'vendors/' + viewModel.count() + '/' + viewModel.filterText()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...