Problem with Url.Content in ASP.NET MVC on Default Route - asp.net-mvc

If I use the following line in my default view /Home/Index
<script language="javascript" src="<%=Url.Content("~/Scripts/jquery-1.3.2.js")%>" type="text/javascript" ></script>
If I surf to this location using the following url http://127.0.0.1:9999/Home/Index
the page gets rendered correctly
<script language="javascript" src="/Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
If I use the following url http://127.0.0.1:9999/ (default wired to Home/Index) the page renders this:
<script language="javascript" src="//Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
Does anyone has any idea how to solve this issue?
EDIT:
FYI: I'm using ASP.NET mvc 2 RC
And this is my route configuration:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);

If you use IIS6 or WinXP Cassini you should register one more route:
if (Environment.OSVersion.Version.Major < 6) // IIS6 and WinXP Cassini
{
routes.MapRoute(
"Root",
"",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
}

I had a very similar problem with Asp.net using Request.ApplicationPath... and wrapped it as follows
public string AppRoot()
{
var appPath = Request.ApplicationPath;
if (appPath.EndsWith("/"))
return appPath;
else
return appPath + "/";
}

Well, alternatively you can do the following:
create a key in appSettings section of web.config file.
<add key="DomainName" value="http://http://127.0.0.1:9999/" />
Now, whenever you want to assign "src" value of any image, javascript of css file, you can use this key. it will be define a root for you and after that you can define at what path you have placed your file. i.e. in your case:
<script language="javascript" src="<%=System.Configuration.ConfigurationManager.AppSettings["DomainName"] %>Scripts/jquery-1.3.2.js" type="text/javascript" ></script>

Why are you keeping your id as an empty string? I think this may be causing the problem. You may find better results by trying the following:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
to this
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", UrlParameter.Optional } // Parameter defaults
);

Related

Select .state on page reload angularjs(using angular-ui-router)

I am developing a ASP.NET MVC 5 application. I am loading a partial view through angular 'ui.router' on a div in a parent page. Routing is working great until I refresh the page - than a partial view is loading on a whole page but I want it to still load as a partial.
This is my code. A parent view, FirstPage.cshtml:
<html ng-app="myApp">
<head>
<base href="/">
<title>First Page</title>
<script src="/Scripts/Angular/angular.js"></script>
<script src="/Scripts/Angular/angular-ui-router.js"></script>
<script src="/Scripts/app.js"></script>
</head>
<body>
<h1>First Page</h1>
<ul id="myMenu">
<li ui-sref="customer">Customer</li>
</ul>
<div ui-view="containerOne"></div>
</body>
</html>
This is my app.js:
var myApp = angular.module("myApp", ['ui.router']);
var proposalConfig = function ($stateProvider, $locationProvider) {
$locationProvider.hashPrefix('!').html5Mode(true);
$stateProvider
.state('customer', {
url: 'Proposal/Customers',
views: {
"containerOne": {
templateUrl: '/Proposal/Customers'
}
}
});
}
proposalConfig.$inject = ['$stateProvider', '$locationProvider'];
myApp.config(proposalConfig);
My RouteConfig.cs:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "ProposalCustomers",
url: "Proposal/Customers",
defaults: new { controller = "Proposal", action = "Customers" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
My ProposalController.cs:
public ActionResult Customers()
{
return View();
}
public ActionResult FirstPage()
{
return View();
}
My Views/Proposal/Customers.cshtml:
<h2>Customer list</h2>
I hope my problem is clear.
EDIT:
I changed my RouteConfig.cs following the solution from this article:
http://www.codeproject.com/Articles/806500/Getting-started-with-AngularJS-and-ASP-NET-MVC-P
to have a default route like this:
routes.MapRoute(
name: "Default",
url: "{*url}",
defaults: new { controller = "Proposal", action = "FirstPage" }
When I refresh a page that has a route exactly like my controller/action, it still loads that specific route on a whole page instead as a partial. If I change a .state url to something else page refresh is working. But still if I put manually a controller/action path in the URL, it shows a view on a whole page instead as a partial.
Is there a way to avoid this?
You need to change you ng-view to ui-view as you are using angular $stateProvider not angular $routeProvider
HTML
<body>
<h1>First Page</h1>
<ul id="myMenu">
<li ui-sref="customer">Customer</li>
</ul>
<div ui-view=""></div>
</body>
You stateProvider should be change which is currently using single view and you declared it as like you are using nested-views
Config
var myApp = angular.module("myApp", ['ui.router']);
var proposalConfig = function($stateProvider, $locationProvider, $urlRouterProvider) {
$locationProvider.hashPrefix('!').html5Mode(true);
$urlRouterProvider.otherwise('/Proposal/Customers'); //default redirection if no route matched
$stateProvider.state('customer', {
url: '/Proposal/Customers',
templateUrl: '/Proposal/Customers',
controller: 'someController' //if you want
});
}
proposalConfig.$inject = ['$stateProvider', '$locationProvider'];
myApp.config(proposalConfig);
Hope this could help you, Thanks.
Ok, so what I'm guessing is happening is you mapped a route in your MVC application to serve the same route as your angular application, in this instance, you mapped 'Proposal/Customers' in your MVC router and in your Angular-UI-Router.
So what is happening is that if you're already in your Angular application, the Angular router has control and as you navigate around, it is loading the template as a child template and putting the HTML into the correct location. When you refresh, you're sending that route to the MVC router, though, and it's serving the HTML as the page.
EDIT
Forgot to mention, this is happening because you've got html5 routing turned on.

Customizing Routes in ASP.NET MVC4

When executed Search Controller - Index
public ActionResult Index(string parm1, string parm2)
Currently URL shows /Search/Index?parm1=aa&parm2=bb
I want to show /Search/aa/bb
I changed the mapRoute to:
routes.MapRoute(
name: "SearchList",
url: "Search/{action}/{parm1}/{parm2}",
defaults: new
{
Controller = "Search",
action = "Index",
parm1= UrlParameter.Optional,
parm2= UrlParameter.Optional
});
what am I missing?
Here's just a straight forward approach to make url change with search term. This is not out of the box and it won't have any exact binding to your route table, if you changed your route, then you have to manually fix it in the javascript. Also you may need to do some null/empty check when generating the url.
$("input.search_term").change(function (e){
//Get search terms and build new url
var parm1 = $("input.search_term[name='parm1']").val();
var parm2 = $("input.search_term[name='parm2']").val();
var newUrl = "/search/"+ parm1 + "/" + parm2;
//Change the link url, can do same thing on a form action url as well
$("a.search_link").attr("href",newUrl);
//For showing the text below, not necessary
$("b.t_link").html(newUrl);
});
<input type="text" class="search_term" name="parm1" value="aa" />
<input type="text" class="search_term" name="parm2" value="bb" />
<a class="search_link" href="/search/aa/bb">Search</a>
<!--not necessary-->
<br />
<span>URL of the link will be: <b class="t_link"></b></span>
<!--I assume you use jquery, let me know if you don't-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Try this:
routes.MapRoute(
name: "SearchList",
url: "Search/{parm1}/{parm2}",
defaults: new
{
Controller = "Search",
action = "Index",
parm1 = UrlParameter.Optional,
parm2 = UrlParameter.Optional
});

.net MVC4 Form submit generates ? instead of / in url -- wrong routing?

i'm kinda new to asp.net mvc4 and try to get some practise now. after some research about routing i still got a problem to pass parameters after a form submit.
my form looks like this:
#using (Html.BeginForm("Index", "Resplaner", FormMethod.Get, new { name = "navigation", id = "navigation" }))
{
<select name="id" size="15" id="nav_menu">
#foreach (var categorie in Model.Categories)
{
<optgroup label="#categorie.Name">
#foreach (var ressource in Model.Ressources)
{
if (#categorie.Id == ressource.Type)
{
<option value="#ressource.Id">#ressource.Name</option>
}
}
</optgroup>
}
</select>
}
which is submitted by the following java script:
$('#nav_menu').on('click', function (event) {
if ($(event.target).is("option")) {
var form = $(event.target).parents('form');
form.submit();
}
});
my actual routes are configurated like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Resplaner",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Resplaner", action = "Index", id = UrlParameter.Optional }
);
so my problem is right now that my generated url after the form submit looks like this
http://localhost:62456/Resplaner?id=6
but my desired url look should look like this
http://localhost:62456/Resplaner/Index/6
if i type the second url manually to my browser, the correct result is shown... thats why i guess there is something wrong in the way how i submit my form. or my routes are still messing up.
i already did some example tutorials about forms in mvc4 but they are always used in a different case like my. so i would be happy about a helping hand.
i am thankful for every help :)
greetings Kurn
Here goes my solution -
Have your html like this -
#using (Html.BeginForm("Index", "Resplaner", new { name = "rami", id = "1" }, FormMethod.Get))
{
// ....
}
Then have a route this way -
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{action}/{name}/{id}",
defaults: new { controller = "Resplaner", action = "Index" }
);
Then your jquery hits the form submit, your URL is going to be -
And the URL is going to be - http://localhost:5738/Resplaner/Index/rami/1?
NOTE: If you do not want that Question mark at the end, then make a POST instead of GET.
The other solution would be to use Hidden Fields -
#using (Html.BeginForm("Index", "Resplaner", FormMethod.Get))
{
#Html.Hidden("id", "1");
#Html.Hidden("name", "rami");
<input type="submit" value="click"/>
}
But again this approach will give you - http://localhost:5738/Resplaner/Index?id=1&name=rami
One more Alternative is to create a #Html.ActionLink() with the required URL and make it click in jquery.
Ok fixed it on another way.
To fix my actual problem i just added a new action in my Controller which receive the form parameter with the question mark and simply do a redirect to the desired url.
[HttpGet]
public ActionResult IndexMap(String id = "1")
{
return RedirectToAction("Index", "Resplaner", new { id = id });
}
It may be not the best way to do it because of the second server call. but for my project i dont see any performance issues since it will be only used in an intranet.
http://localhost:62456/Resplaner/IndexMap?id=2 will redirect to http://localhost:62456/Resplaner/Index/2
I would like to thank everyone who tried to help me. You gave me some great suggestions and ideas.

mvc2 host on iis6 : The incoming request does not match any route

I have to host my project on iis6, I can not change iis setting on server.
So, I modified global.asax like below.
If I add a default.aspx and browse project I got error like : The incoming request does not match any route.
if I dont add default aspx I got HTTP Error 403.14
have any idea?
thanks
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Default", // Route name
"{controller}.aspx/{action}/{id}",
new { controller = "Home", action = "Index", id = "" } // Parameter defaults )
);
routes.MapRoute("Detail", // Route name
"{controller}.aspx/{action}/{id}/{sid}",
new { controller = "Home", action = "Index", id = "", sid="" } // Parameter defaults )
);
routes.MapRoute("ForGoogle", // Route name
"{controller}.aspx/{action}/{friendlyUrl}/{id}/{partialName}",
new { controller = "Home", action = "Index", friendlyUrl = "", id = "", partialName =""} // Parameter defaults )
);
routes.MapRoute(
"PostFeed",
"Feed/{type}",
new { controller = "Product", action = "PostFeed", type = "rss" }
);
}
Add an index.htm file which redirects to the right page. This has a side advantage: it does not require the webapp to be started, so it is possible to show an image or text while the webapp is started for the first time.
A fancy jquery "loading..."-page I use in some projects:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>(loading...)</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({ type: 'GET', url: 'Home.aspx', success: function() { location.href = 'Home.aspx'; } });
});
</script>
</head>
<body>
<div id="loading">
(show "loading..." text here)
</div>
</body>
</html>

Can Asp.Net Mvc Route Constraints throw a 404 instead of InvalidOperationException?

I'm trying to use route constraints in an Asp.Net MVC Application.
routes.MapRoute(
"theRoute",
"MyAction/{page}",
new { controller = "TheController", action = "MyAction", page = 1 },
new { page = #"[0-9]" });
When I enter an url like ~/MyAction/aString, an YSOD is shown with an invalid operation exception. What can I do to redirect invalid url to the 404 page?
I know I can solve the issue with a string parameter in the controller action and int.TryParse, but then the route constaint is useless.
How can I choose the exceptiontype that is thrown by the route constraints?
The problem is that you do not have a route that matches the route that ends in a string.
Modify your routes similar to:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = 0 },
new { id = "[0-9]" }// Parameter defaults
);
routes.MapRoute(
"Default2", // Route name
"{controller}/{action2}/{sid}", // URL with parameters
new { controller = "Home", action = "Index2", sid = "" } // Parameter defaults
);
and modify your controller
public ActionResult Index(int id)
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC! Your id is: "+ id.ToString();
return View();
}
public ActionResult Index2(string sid)
{
ViewData["Title"] = "Home Page 2."+sid.ToString();
ViewData["Message"] = "Welcome to ASP.NET MVC! \"" + sid.ToString() +"\" is an invalid id";
return View("index");
}
now when you pass a string for the ID, Index2 will be called and you can do whatever you need to do to handle the incorrect parameter.
Just to mention a more general redirection:
You can write in the Web.config of your application:
<system.web>
...
...
<customErrors mode="On">
<error
statusCode="404"
redirect="/Home/MyCustomError" />
<!-- Is not necessary that the
view MyCustomError.aspx are inside the
Home folder, you can put that
view in the Shared folder.
-->
</customErrors>
...
...
</system.web>
Then you need to have an ActionResult called MyCustomError
public class HomeController : Controller
{
...
...
public ActionResult MyCustomError(string aspxerrorpath)
/* the var aspxerrorpath
* is that MVC generated by
* default */
{
ViewData["messageError"] = aspxerrorpath;
return View();
}
}
Then you can make a custom error page:
<%# Page Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>
<asp:Content ID="errorTitle" ContentPlaceHolderID="TitleContent" runat="server">
Error
</asp:Content>
<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>Shit happends</h2>
<p> <%: ViewData["messageError"]%></p>
<p>aaaaaaaaaaaaaaa!!!!!!!!!!!!!!!!!!!!</p>
</asp:Content>

Resources