building relative URLs for an MVC app with JavaScript

后端 未结 3 2009
不思量自难忘°
不思量自难忘° 2020-12-17 20:24

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 fire

3条回答
  •  独厮守ぢ
    2020-12-17 21:01

    One possibility is to send those javascript values as request parameters:

    $.ajax({
        url: '@Url.Action("vendors")',
        data: { count: viewModel.count(), filter: viewModel.filterText() },
        dataType: 'json',
        success: function (data) {
            viewModel.vendors(data);
        }
    });
    

    Of course this implies that you are using default routes and the parameters will simply be sent to the server either as query string parameters (if you are using GET) or as part of the POST request body. In both cases you will fetch them on the server the same way:

    public ActionResult Vendors(int count, string filter)
    {
        ...
    }
    

    Another possibility, if you absolutely insist on having some custom routes for your AJAX requests, would be to use a simple string replace:

    var url = '@Url.Action("vendors", new { count = "__count__", filter = "__filterText__" })';
    url = url.replace('__count__', viewModel.count())
             .replace('__filter__', viewModel.filterText());
    $.ajax({
        url: url,
        dataType: 'json',
        success: function (data) {
            viewModel.vendors(data);
        }
    });
    

提交回复
热议问题