Reputation: 6070
I am new in ASP.Net.
I want to have URLs like:
http://example.com/Controller/Action
Right now I am calling URL from script is like this:
$('#datatable').dataTable({
"aoColumnDefs": [{ 'bSortable': false, 'aTargets': [-1] }],
"oLanguage": { "oPaginate": { "sPrevious": "", "sNext": "" } },
"iDisplayLength": 5,
"aLengthMenu": [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"sDom": 'T<"panel-menu dt-panelmenu"lfr><"clearfix">tip',
"oTableTools": {
"sSwfPath": "vendor/plugins/datatables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf"
},
"sAjaxSource": "admin/Categories",
});
Currently using relative URL:
"sAjaxSource": "admin/Categories/Index/"
The problem with this URL is it is relative URL, but I want to define the base URL before defining the controller and action.
How can I implement this in .cshtml file under <script>
tag?
If I am doing it the wrong way, then I would be keen to learn the right way to implement the URLs for AJAX calls?
Sorry, I forgot to mention, I am using MVC Areas, I want to have Base URL for Areas. Admin is defined under Areas directory.
Upvotes: 0
Views: 2162
Reputation: 6553
What I've found works best is to define your base url in the html in your layout
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="@Functions.GetApplicationPath(Request)" />
// Other header stuff
</head>
And define that @Functions in your App_Code
folder (might have to create it)
@functions {
public static string GetApplicationPath(HttpRequestBase request)
{
// Gets the base url in the following format: "http(s)://domain(:port)/AppPath);
var applicationPath = request.Url.Scheme + "://" + request.Url.Authority + GetApplicationType(request);
if (string.IsNullOrWhiteSpace(applicationPath) || !applicationPath.EndsWith("/"))
{
applicationPath += "/";
}
return applicationPath;
}
public static string GetApplicationType(HttpRequestBase request)
{
var applicationType = request.ApplicationPath;
return applicationType;
}
}
This lets you separate out your cshtml and your javascript so you can use relative urls and the base url will handle any website prefixes like http://yoururl/blah/actualsiteHere
Upvotes: 2
Reputation: 3763
The best way to generate your action url is :
@Url.Action("ActionName", "ControllerName", new { area = "AreaName" })
Upvotes: 3
Reputation: 21191
If you are using a script tag within a Razor view, you can use the UrlHelper:
'sAjaxSource': '@Url.Action("index", "categories", new { area = "admin" })'
Otherwise, you can also make it a root-based URL with:
"/admin/Categories"
Upvotes: 1