Relatve and Absolute path in JQUERY Ajax

$.ajax( { type: "GET", url: 'Home/GetMsg', success: function (result) { }, error: function (req, status, error) {} }); 

By default, the relative path for Home / GetMsg is used. I call this function from different controllers / views that break the URL. How can I name the absolute and relative path here. I tried with the URL: 'http://abc.com/Home/Getmsg', but again does not work

+4
source share
2 answers

Use Assistant:

 url: '@Url.Action("GetMsg", "Home")', 

or if it is in a separate javascript file where you cannot use server-side helpers, you can use helpers to generate a URL for some existing DOM element using data- * HTML5 attributes:

 <div id="foo" data-url="@Url.Action("GetMsg", "Home")">Foo</div> 

and then in js:

 url: $('#foo').data('url'), 
+8
source

Since you are using MVC, you can search for Url.Action :

 @Url.Action("GetMsg","Home") 

Also, if you intend to use paths in Javascript, it might be a good idea to use hidden elements with this path so that you can use Javascript from the outside, for example:

 @Html.Hidden("GetMsgPath",Url.Action("GetMsg","Home")) $.ajax({ type: "GET", url: $("#GetMsgPath").val(), success: function (result) { }, error: function (req, status, error) {} }); 
+3
source

Source: https://habr.com/ru/post/1385209/


All Articles