Intro
I'm developing a project with MVC.Net. I have just started a default website with a Home Controller and an Index action. I browse to the view with 'Home/Index/1' and everyting works fine.
Now I want to add an extra url parameter, so I've changed my global.asax and added a foo parameter:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}/{foo}", // URL with parameters
new {controller = "Home", action = "Index", id = UrlParameter.Optional, foo = UrlParameter.Optional} // Parameter defaults
);
On the page I also have a little bit of jquery. For example this script:
<script type="text/javascript">
$(document).ready(
function ()
{
});
</script>
Problem
But now when I browse to my page with 'Home/Index/1/1' I get a javascript error:
Microsoft JScript runtime error: Object expected
When I browse to the page with 'Home/Index/1' everything works fine. Probably there's a problem with my url routing, but I have no clue what I'm doing wrong.
You can also use the following syntax to force the resolution of the path
<script src="<%: Url.Content("~/Scripts/jquery-1.4.1.js") %>" type="text/javascript">
The cause of the problem is your Script source location. I assume your script source is ../../Scripts/jquery.js which this is always being created by the application when you attach a js file in your page.
Explained.
js file mapped in `../../Scripts/jquery.js`
Page is `Home/Index/1/1`
js real content is placed in `/Scripts`
when the parser looks for the js it looks in `/Home/Scripts`
which is not where it where it is. Since ../.. = /Home in Home/Index/1/1
My Suggestion is
<%
string baseUrl = "http://" + Request.Url.Host + (Request.Url.Port != 80 ? ":" + Request.Url.Port.ToString() : "");
$>
<script type="text/javascript" language="javascript" src="<%=baseUrl %>/Scripts/jquery-1.4.1.js"></script>
This also goes to your CSS files included in your page. But for CSS links you don't put " in your href attribute of the <link> tag
Related to my answer in here
Related
I have an asp.net mvc site to which I've added some knockoutjs. The knockout code makes ajax request for data from the controllers e.g.
$.getJSON(BASE_URL + 'MyTasks/GetDataPage', { userKey: vm.UserKey, pageSize: pageSize }, function (returnedPayload) {
data = returnedPayload.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
self.setPagingData(data,page,pageSize);
The BASE_URL constant I set in the <head> of my layout razor page as follows:
<script type="text/javascript">
var BASE_URL = '/bamportal/';
</script>
All works fine when the website is deployed. However, when I run the website from VS by hitting F5 then I get a 404 such as:
http://localhost:49601/bamportal/MyTasks/GetDataPage?userKey=2&pageSize=50 Failed to load resource
If it had tried to address "http://localhost:49601/MyTasks/GetDataPage" (without the "/bamportal/") it would work.
What's the best solution for this problem?
Quick and dirty:
<script type="text/javascript">
var BASE_URL = '#Constants.BaseUrl';
</script>
where Constants is a static class defined as:
public static class Constants {
#if DEBUG
public const string BaseUrl = "/";
#else
public const string BaseUrl = "/bamportal/";
#endif
}
So when you compile your application in debug configuration you will get /, while in release you will get /bamportal/.
As alternative, a more complex and versatile approach could be obtained using Configuration Transforms and appSettings from Web.config:
<script type="text/javascript">
var BASE_URL = '#System.Configuration.ConfigurationManager.AppSettings["BaseUrl"];';
</script>
This, of course, will be extremely useful in scenarios where you need to deploy front-end and back-end on different domains/urls.
Your code should never know where the site will be hosted, you should use the correct helpers to determine where the action/content is located, this will prevent any issues with paths. Use Url.Content and Url.Action they will generate the correct path/url in the code.
As an example your action needs to point to the "MyTasks", "GetDataPage"
In your razor code you should have something like
<div id="urls" data-url="#Url.Action("ActionMethodName","YourControllerName")"></div>
Then in your get code get that stored url
$.getJSON($("#urls").data("url"),
To elaborate further this code will work on any environment (production, debug, iis, any location) without any developer worry or tweaking with config files or any other process. Tomorrow if you need to host your site on "osportal" not "bamportal" no changes need to be made, this should not be part of your code base.
One of the biggest benefits is that if the controller or action ever change the compiler will let you know that the url does not exist and you can fix it. Hardcoding paths/urls/location is a very bad/unmaintainable practice.
I started learning Rails 3 months ago.And now I'm trying to add Ajax in my Rails app.
So it have some problems.
In my Index.html.erb file:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","demo.txt", true);
xhttp.send();
}
</script>
<button type="button" onclick="loadDoc()">click</button>
<p id="demo"></p>
And I created a file that demo.txt.I try to show content in demo.txt when I click the button.But it shows nothing.
So have any tut for me.
Thanks !
The second parameter of the xhttp.open(...) call should be a URL, not simple a file name. If you are running the Rails application with "rails s" then your url might look something like "http://localhost:3000/demo.txt" if the file demo.txt is in your public folder. Without a URL in that second parameter, I suspect that the request is never finding your rails application.
You might also want to dig into jquery (since you tagged it) to understand how to use that library to issue the request. The interface is much simpler than the low-level js.
I m having one index page and one child page. In my index page, I m trying to render my child. but somehow things not working as expected and Angular routing not working as expected
Here is my index page
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<body ng-app="AngularApp">
<div> My message {{message1}} </div>
First child
<div></div>
<div ng-view></div>
</body>
#section scripts{
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Scripts/angular-resource.js"></script>
<script src="~/Modules/AngularApp.js"></script>
}
Here is my angularApp.Js file where I have defined the routing
var myapp = angular.module('AngularApp', ['ngRoute']);
myapp.config(function ($routeProvider, $locationProvider) {
$routeProvider.when('/',
{
templateUrl: '/Index',
controller: 'IndexController'
})
.when('/FirstChild',
{
templateUrl: '/Angular/FirstChild',
controller: 'ChildController'
});
$locationProvider.html5Mode(true).hashPrefix('!')
});
myapp.controller('IndexController', function ($scope) {
alert('My Index');
$scope.message1 = "My Index";
});
myapp.controller('ChildController', function ($scope) {
alert('My Child Index');
$scope.FirstMessage = 'My First Message';
});
Here is my ASP.NET MVC Action for rendering the partial view. My controller name in ASP.NET MVC is Angular
public ActionResult FirstChild()
{
return PartialView("Firstchild");
}
Problem 1:
When I run the application with Index as the start page, this is the URL, I m seeing in the browser, http://localhost:59367/Angular/Index but the corresponding controller in Angular side for index page is not triggered
Problem 2:
When I click the First child link in my index page, its taking me to a completely page rather than rendering the partial view inside the ng-view.
http://localhost:59367/Angular/FirstChild
I m pretty sure there is serious problem in Angular routing which I defined but couldn't figure it out:( Please help
Problem Summary:
On further analysis, its been found that, once I click the "First child", ideally the URL should read like Angular/Index#/FirstChild but what happens here is, "ASP.NET MVC Action First Child is getting called and the URL is changing completely"
Problem has been identified. The article which I followed has used the below part
$locationProvider.html5Mode(true).hashPrefix('!')
in the app.js file. I have removed it due to some issues in my local. But while doing so, I didn't update the part in my index page for this line
First child
It has to be
First child
Now angular routing started working fine without any issues. :)
Updated Question:
I tried including the line in d code and I removed as # in my the href but it was not working.. Seems like angular routing has to be updated as well.
$locationProvider.html5Mode(true).hashPrefix('!')
Can someone help me in updating it in the correct format.
I have the following MVC route:
routes.MapRoute("AccountLookupDirect",
"{culture}/account/{originalSellerId}/{accountNumber}",
new {culture = "en-gb", controller = "accountlookup", action = "index", originalSellerId = UrlParameter.Optional, accountNumber = UrlParameter.Optional},
new {culture = #"[a-z]{2}-[a-z]{2}"}
);
I can browse to a url such as http://{server}/**account**/{seller}/{accountnumber} and the page loads as expected. The problem is that when links are generated on a page, the url is not updating to the new route. Instead I get http://{server}/**{controller}**/{seller}/{accountnumber}.
The links are generated dynamically using Handlebars templating. The template looks like:
<script type="text/x-handlebars-template" data-template-name="account-link">
{{ AccountNumber }}
</script>
I have deployed the same code on two different servers and it works as expected on one, but not the other.
It seems that the cause of this issue was because the servers have a different version of the .NET framework installed. The working server has .NET 4.5 whereas the other only has .NET 4.
Unfortunately as we couldn't install 4.5 on one of the boxes we had to implement a very ugly workaround:
<script type="text/x-handlebars-template" data-template-name="account-link">
{{ AccountNumber }}
</script>
Does anyone has example, How to redirect to a new page in Jquery with MVC?
thank you
It's done as Darin says. Note that you might want to use a relative uri. The easiest way is to define a variable that contains the base uri (I'm using Razor view engine in the example).
<script type="text/javascript">
var baseUri = '#Url.Content("~/")';
function redirect() {
window.location.href = basUri + 'new/url';
}
</script>
You don't really need jquery for this. It can be done using the window.location.href property which will redirect the browser to the given url:
window.location.href = '/new/url';
to new page, do this:
window.location = 'welcome.php';
window.location = '#Url.Action("action","Controller")';*It gets in the way*