Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...