I'm having a problem using parameters in Durandal for an ASP.NET MVC application...
I use MVC Route Attributes, for example:
[Route("admin/pages")], [Route("admin/blog")], etc..
And I integrate Durandal as follows:
main.js:
app.start().then(function() {
viewEngine.viewExtension = '/';
viewLocator.convertModuleIdToViewId = function (moduleId) {
return moduleId.replace('viewmodels', '');
};
app.setRoot('viewmodels/admin/shell', 'entrance');
});
This works nicely, as the viewId ends up matching the MVC route.
However, I now face a serious problem with trying to use parameters in the routes. For example, I have one route as follows:
[Route("admin/localization/localizable-strings/{languageId}")]
and my Durandal route for this is:
localization/localizable-strings/:languageId
Example anchor tag:
Localize
This doesn't work, as it seems Durandal doesn't pass the parameter to the server. It simply retrieves the HTML from /admin/localization/localizable-strings which returns a 404 page because no parameter was passed to the MVC action.
What are my options here?
I know this question is almost 2 years old now, but I obviously forgot to close it with my solution at the time. Basically, Brett and Marvin were correct, but since I was so new to Durandal (and SPAs in general) at the time, I misunderstood exactly what they were telling me. I ended up doing this:
self.cultureCode = null;
self.activate = function (cultureCode) {
self.cultureCode = cultureCode;
if (!self.cultureCode) {
self.cultureCode = null;
}
};
And the durandal route was set up as follows;
"localization/localizable-strings/:cultureCode"
I would then use that parameter to obtain the relevant data via ajax. My mistake was wanting the parameter to be able to be used in the MVC action method so that I could obtain some data server side, which of course doesn't work...
Related
In Asp.Net MVC, the Account controller's Login method, if successful, returns RedirectToLocal(returnUrl);
I want to add a string to return. I thought ViewBag or TempData would do, but the View finds those to be empty. So I guess those don't get passed to the View, even though that's their exact purpose, from what I read.
There's got to be an easy way...other than returning to Classic ASP.
It sounds like you want to declare (optional?) parameters on the route you're redirecting to.
For example, something like:
return RedirectToAction("Action", new { id = 99 });
Here are a few links that might help:
MVC RedirectToAction passing route parameters
Passing data from one controller to another in ASP.NET MVC
PS:
Please don't return to "Classic ASP.Net" (or "even-more-classic ASP 3.0" ;)). Get familiar with MVC, and look forward to ASP.Net Core (which is MVC from the ground up ;))
I am very new to MVC and trying to migrate asp.net application to MVC. Basically I am trying to reuse the code where ever possible. In one case I was trying to use Redirect("SomeUrl") and it works pretty well with the view under same controller.
For eg., I added below piece of code in HomeController.cs
public ActionResult Login()
{
return Redirect("HomeMgr?Section=home&Type=Mgr");
}
Well, could someone suggest me if I can use Redirect(Url) to redirect to a view in another Controller? is there any format for Url something like
"~/controllername/Viewname?something=something&something=otherthing"
(I've read in other posts that I can achieve this using RedirectToAction, but I am trying not to change existing code which uses querystring values. )
Don't use Redirect to redirect to Actions in your app. There are several reasons for this. First, it's just simpler to user RedirectToAction as Alundra's answer provides. However, simpler is only part of the answer.
There's a problem with using Redirect. And that has to do with the way Routing works in MVC. In MVC, you can reach the same action via multiple different URL's. For instance, in a default MVC template, the following are all valid URL's.
http://yoursite/
http://yoursite/Home
http://yoursite/Home/Index
Now, what happens when you use Redirect? If you use the last url, it will work fine. You'll end up with the following url.
http://yoursite/Home/HomeMgr?Section=home&Type=Mgr
But if you're at any of the others, you have a problem...
http://yoursite/HomeMgr?Section=home&Type=Mgr
Oops... that won't work... That will be looking for a controller named HomeMgrController.
You get the same at the root as well.
Using RedirectToAction solves this problem, as it takes your routing into account and will figure out the correct url to redirect you to based on the Controller and Action you specify.
return RedirectToAction("ActionName", "ControllerName", new { Section=home,Type=Mgr ......Anythingelse you want to pass });
This is a more specific version of another of my questions: Restful MVC Web Api Inheritance, I hope an answer to this will help me answer that.
Im using ASP.NET web api,
I want to be able to route something like this: [{object}/{id}]/{controller}/{id}.
so i want an array of objects with optional /{id} ending with the 'api endpoint'.
I want to be able to route these:
/houses
/houses/3
suburbs/3/houses
council/5/suburbs/houses
city/8/council/suburbs/houses
ETC
TO
get(List<restRoute>parents, int id){
...
}
restRoute would be an object with a string for the object and an optional int (or guid etc) for the id
Does anyone know where i can start?
I don't want to route every single one individually.
I had also such problems with routing from the box in ASP.NET MVC. Its good way to be used as common routing, but is not so flexible for custom routs.
In WCF Web Api (ASP.NET web api in CTP version) was used attribute based routing.
I think its more flexible, but as negative point - each method should have routing attribute.
Take a look at this blog post:
http://www.strathweb.com/2012/05/attribute-based-routing-in-asp-net-web-api/
It describes how to implement attribute based routing using ASP.NET Web Api. Because such approach is more flexible for routes you can map to methods, it can be helpful for you.
You could use the {*anything} Variable Segmented URL pattern in your route and handle the splitting up and figuring out of what part of the url corresponds to what bit of data in your method:
Global.asax:
routes.MapRoute(
"Special", // name
"{*allthethings}", // parameters
new { controller = "Special", action = "Sauce" } // defaults
);
SpecialController:
public ActionResult Sauce()
{
string data = RouteData.Values["allthethings"].ToString();
string[] items = data.Split('/');
foreach (string item in items)
{
// do whatever you need to figure out which is what!
}
return View();
}
If you wanted to be a bit cleverer about it you could create your own custom RouteHandler to do the splitting. Something like David Ebb's PK routehandler would probably do the trick, with some customisation to fit your requirements in the processing of the route. You could use this to split up the "allthethings" parameter and turn it into your List<RestRoute> format before passing the request on to the Controller
I'm diving into ASP.NET MVC and I'm coming from a Ruby on Rails background. I'm trying to understand how ASP MVC handles AJAX functionality and, after reading some of the tutorials on the ASP website, it appears they implement AJAX functionality very differently. One of the ways that RoR handles AJAX functionality is by returning ruby-embedded javascript code that is executed as soon as it is received by the browser. This makes implementing AJAX really simple and quite fun. Can ASP.NET MVC return a javascript response?
just user
return JavaScript(script)
You would have to execute the java script manually on the View
To be more specific you can make the controller action return type JavaScriptResult
What you are talking about is called javascript generators in the RoR world and there's no equivalent in the ASP.NET MVC world. Here's a blog post that illustrates the basics of implementing a Rails-like RJS for ASP.NET MVC (the blog post uses prototypejs but could be easily adapted to work with jquery).
Here's another approach using jquery:
public ActionResult Foo()
{
return Json(new { prop1 = "value1", prop2 = "value2" });
}
and to consume:
$.getJSON('/home/foo', function(result) {
// TODO: use javascript and work with the result here,
// the same way you would work in a RJS like template
// but using plain javascript
if (result.prop1 === 'value1') {
alert(result.prop2);
}
});
Also worth taking a look at is JsonResult which extends ActionResult. I usually use this when making AJAX requests for data of some sort.
Up until now I've been able to get away with using the default routing that came with ASP.NET MVC. Unfortunately, now that I'm branching out into more complex routes, I'm struggling to wrap my head around how to get this to work.
A simple example I'm trying to get is to have the path /User/{UserID}/Items to map to the User controller's Items function. Can anyone tell me what I'm doing wrong with my routing here?
routes.MapRoute("UserItems", "User/{UserID}/Items",
new {controller = "User", action = "Items"});
And on my aspx page
Html.ActionLink("Items", "UserItems", new { UserID = 1 })
Going by the MVC Preview 4 code I have in front of me the overload for Html.ActionLink() you are using is this one:
public string ActionLink(string linkText, string actionName, object values);
Note how the second parameter is the actionName not the routeName.
As such, try:
Html.ActionLink("Items", "Items", new { UserID = 1 })
Alternatively, try:
Items
Can you post more information? What URL is the aspx page generating in the link? It could be because of the order of your routes definition. I think you need your route to be declared before the default route.
Firstly start with looking at what URL it generates and checking it with Phil Haack's route debug library. It will clear lots of things up.
If you're having a bunch of routes you might want to consider naming your routes and using named routing. It will make your intent more clear when you re-visit your code and it can potentially improve parsing speed.
Furthermore (and this is purely a personal opinion) I like to generate my links somewhere at the start of the page in strings and then put those strings in my HTML. It's a tiny overhead but makes the code much more readable in my opinion. Furthermore if you have or repeated links, you have to generate them only once.
I prefer to put
<% string action = Url.RouteUrl("NamedRoute", new
{ controller="User",
action="Items",
UserID=1});%>
and later on write
link
Html.ActionLink("Items", "User", new { UserID = 1 })