Constructing controller action URL within JQuery AJAX call
Using JQuery's ajax() or get() methods we can make an async call 开发者_Python百科to the ASP.NET MVC controller action, for instance like this:
function(){
$.get('<%=Url.Action("TitleToSlug", "Services", new { title = "Some title" }) %>', function (data) {
$('#SomeOtherTextbox).val(data);
});
}
What if we wanted the URL parameter (in the above case "title") to be dynamic e.g. read it from somewhere on the page? Let me say that using Url.Action() helper within ASP.NET MVC code block inside javascript does work but I'm having trouble figuring out how to make the concatenation.
Hope you understand what I want - I want to insert value of the Title textbox there where the "Some title" is.
You could generate your URL server-side with a bogus title (something that would never be used as a real title, like "BOGUS_TITLE") and when the client-side code execute replace it with the actual dynamic value:
function(){
var titleTemplate = '<%=Url.Action("TitleToSlug", "Services", new { title = "_BOGUS_TITLE_" }) %>';
$.get(titleTemplate.replace('_BOGUS_TITLE_', realTitle), function (data) {
$('#SomeOtherTextbox).val(data);
});
}
精彩评论