How to get Asp.Net MVC 3 current project name?
I have an Asp.net MVC 3 project with name of "abc". It shows http://localhost:23543/abc/.... when debugging run in VS. The url will be http://hostname/webAppName/abc/... after publish the pro开发者_开发知识库ject in a virtual folder under the default web site of IIS 7.
However, there is some jQuery ajax call, using '/scripts/...', in a separated external js file. The absolute path of '/scripts/' will become ...wwwroot/abc/scripts/... instead of ...wwwroot/webAppName/abc/scripts/.... I am creating a js function for wrapping the ajax url links.
var fullPath = '@HttpContext.Current.Request.Url.Scheme://@HttpContext.Current.Request.Url.Authority';
function GetPath(projectName, url) {
return fullPath + projectName + url;
}
In js file: ... url: GetPath('/scripts/...')....
How to get the project name? Or is there a better solution?
Use the below code to create the mvc request url
var siteRoot = '@Url.Content("~/")';
function GetPath(url) {
return siteRoot + url;
}
In your markup, you can use a site-relative URL that will be translated to the correct form at runtime:
<script type="text/javascript" src="@Url.Content("~/Scripts/myscript.js")"></script>
Usually in script what I tend to do is AJAXify existing anchor links or forms which already have the proper url as they were generated using HTML helpers.
So for example with a form (generated using Html.BeginForm helper):
$('#myform').submit(function() {
$.ajax(}
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
}
});
return false;
});
or with an anchor (generated using Html.ActionLink helper):
$('#mylink').click(function() {
$.ajax(}
url: this.href,
type: 'POST',
success: function(result) {
}
});
return false;
});
Of course there might be some cases where you need an url other than a link or a form. What I tend to do in those cases is to use HTML5 data-* attributes on some DOM element. For example:
<div id="foo" data-url="@Url.Action("SomeAction", "SomeController")">foo bar</div>
and when I needed this url I would simply:
var url = $('#foo').data('url');
See how we don't need any GetPath function. All the urls are already part of our DOM and in the separate javascript file we simply use them.
加载中,请稍侯......
精彩评论