ASP.NET MVC 3 basic routing question - asp.net-mvc-3

I am using ASP.NET MVC 3 and following the tutorial here http://www.asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs.
I am working on the sign up functionality and trying to make use of routing. So the typical scenario is:
When the user wants to sign up, he would get taken to /Account/SignUp.
Upon succesful sign up, he then gets redirected to /Account/SignUp/Successful.
I thought it would be simple enough but the "Successful" parameter never gets passed in the SignUp method in the controller.
public ActionResult SignUp(string msg)
{
// Do some checks on whether msg is empty or not and then redirect to appropriate view
}
In global.aspx.cs I've got pretty much the vanilla routing:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
What am I failing to grasp here?

Your route parameter is called id, so:
public ActionResult SignUp(string id)
{
...
}
or change it to msg if you want:
"{controller}/{action}/{msg}"

Change the parameter from your method to id and create an get method for the /Account/SignUp action
public ActionResult SignUp()
{
//this is the initial SignUp method
}
[HttpPost]
public ActionResult SignUp(string id)
{
//User will be redirected to this method
}

Related

Action method is not fired after deploying in IIS using Ajax.ActionLink()

I have a default routing as below:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "URLParameter.Optional" } // Parameter defaults
);
}
My Index Action method is returning a list of model to view. And in Index View i have somthing like this:
#Html.ActionLink(article.Title,"Download",new { id = "C:\\Files\file1.txt"},null);
But, AFter deploying in IIS the "Download" action method is not getting fired And getting a 404 PAGE NOT FOUND error.
If I am specifing the action method as 'Index" in Html.ActionLink, Then It's working Like:
#Html.ActionLink(article.Title,"Index",new { id = "C:\Files\file1.txt"},null);
The Above code is working because it's taking the default route after deploying in IIS. I tried to change the routes in Global.asax, But failed to get a solution.
What i need here is, I want the second action method to be fired, which is not.
My 1st Action Method is :
public ActionResult Index() {}
My 2nd Action Method is :
public ActionResult Download(string loc) {} //This is not getting fired..???
Will provide you more details if needed..please Assist, as it will effect my delivery.

Recommended API design with ASP.NET MVC3

I'm working with ASP.NET MVC 3. I'm kind of new to it. I think I'm starting to get the hang of it. But there is something that I'm trying to do, that I think makes sense, but maybe I'm wrong.
I'm trying to create an API around Order objects in my database. In order to get all of the orders in the system, I was going to expose an API that looks like the following:
/orders/
In cases where I wanted to get a specific Order, I would simply append an ID. In other words, the URL would look like this:
/orders/12345
In an effort to accomplish this, I created the following controller:
public class OrdersController : Controller
{
// GET: /Orders/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
string result = "list of orders";
return Json(result, JsonRequestBehavior.AllowGet);
}
//
// GET: /Orders/{orderID}
public ActionResult Index(int id)
{
string result = "order:" + id;
return Json(result, JsonRequestBehavior.AllowGet);
}
}
In my AreaRegistration class, I have the following:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"OrderList",
"{controller}/{action}",
new { action = "Index", controller="Orders" }
);
context.MapRoute(
"Order",
"{controller}/{action}/{id}",
new { action = "Index", controller = "Orders" }
);
}
When I attempted to access "/orders/", via the browser address bar, I get the JSON like I would expect. However, if I attempt to access "/orders/12345", I receive a 404. What am I missing?
Thank you
You need to also define proper routes in global.asax or use the default route which looks like {controller}/{action}/{id} where controller is defaulted to "Home", action is defaulted to "Index" and id is optional.
So /orders works because you have defined controller (orders), default action (Index) and missing id (which doesn't matter as it is optional)
But when you try /orders/12345 then you have defined controller (orders), action (12345) and missing id
So to make this work with only the default route the request should be /orders/index/12345
edit: for registering area routes you should use AreaRegistration class

Add route for asp.net mvc 3

I need to be able to hande routes like this:
appdomain/city/City-state, so in case somebody used
appdomain/Washington/Washington-DC he retrieves proper info from proper controller action. For now can`t get what controller and action it should be to get this url and handle it properly.
To clear it a bit, there`s like no controller and action, but 2 parameters instead of them.
Why not adding a little help from a fixed path, like Show-City
routes.MapRoute(
"CityAndState",
"Show-City/{city}/{state}",
new { controller = "Cities", action = "Index", id = UrlParameter.Optional }
);
this will never interfere with your existing routes, and then you can use:
http://domain.com/Show-City/New York/NY
at your Index Action inside the Cities Controller you would have something like:~
public class CitiesController : Controller
{
public ActionResult Index(string city, string state)
{
// use city and state variables here
return View();
}
}
Try this:
routes.MapRoute("Foo", "{state}/{city}",
new { controller = "ControllerName", action = "ActionName" });
and in your class you'd have:
public class ControllerNameController : Controller {
public ActionResult ActionName(string state, string city) {
...
}
}

Parameter works in ActionResult, but doesn't exist in RouteData in MVC3?

I have a simple ActionResult in my controller:
public ActionResult Index(int productId)
{
return View();
}
If I breakpoint it, I can confirm the productId is being passed through and is not null. However, if I examine my RouteData:
(int)RouteData.Values["productId"]
There's nothing there. There's a key for controller and a key for the action, but nothing for the parameter? What's going on?
Did you declare the productId as token somewhere in your routes?
routes.MapRoute(
"Default",
"{controller}/{action}/{productId}",
new { controller = "Home", action = "Index", productId = UrlParameter.Optional }
);
If you haven't don't expect to find it in the RouteData collection. This collection contains only tokens that were declared in your routes.
The default route uses id (the one generated by Visual Studio wizard), so you could rename your action parameter:
public ActionResult Index(int id)
{
return View();
}
which would totally make sense in a ProductsController for example. And now you will find it in RouteData.Values["id"].

ASP.Net Mvc 3 Url.Action method uses parameter values from previous request

When Urls are autogenerated using the Url.Action helper, if a page contains a line similar to
#Url.Action("Edit","Student")
is expected to generate a url like domain/student/edit and its working as expected.
But if the requested url contains some parameters, like domain/student/edit/210, the above code uses these parameters from the previous request and generates something similar even though I've not provided any such parameter to the Action method.
In short, if the requested url contains any parameters, any auto generated links of the page (served for that request) will include those parameters as well no matter if I specify them or not in the Url.Action method.
What's going wrong?
Use Darin's answer from this similar question.
#Url.Action("Edit","Student", new { ID = "" })
Weird, can't seem to reproduce the problem:
public class HomeController : Controller
{
public ActionResult Index(string id)
{
return View();
}
public ActionResult About(string id)
{
return View();
}
}
and inside Index.cshtml:
#Url.Action("About", "Home")
Now when I request /home/index/123 the url helper generates /home/about as expected. No ghost parameters. So how does your scenario differs?
UPDATE:
Now that you have clarified your scenario it seems that you have the following:
public class HomeController : Controller
{
public ActionResult Index(string id)
{
return View();
}
}
and inside Index.cshtml you are trying to use:
#Url.Action("Index", "Home")
If you request /home/index/123 this generates /home/index/123 instead of the expected /home/index (or simply / taken into account default values).
This behavior is by design. If you want to change it you will have to write your own helper which ignores the current route data. Here's how it might look:
#UrlHelper.GenerateUrl(
"Default",
"index",
"home",
null,
Url.RouteCollection,
// That's the important part and it is where we kill the current RouteData
new RequestContext(Html.ViewContext.HttpContext, new RouteData()),
false
)
This will generate the proper url you were expecting. Of course this is ugly. I would recommend you encapsulating it into a reusable helper.
Use ActionLink overload that uses parameters and supply null
You could register custom route for this action for example:
routes.MapRoute("Domain_EditStudentDefault",
"student/edit",
new {
controller = MVC.Student.Name,
action = MVC.Student.ActionNames.Edit,
ID = UrlParameter.Optional
},
new object(),
new[] { "MySolution.Web.Controllers" }
);
you then could use url.RouteUrl("Domain_EditStudentDefault") url RouteUrl helper override with only routeName parameter which generates url without parameters.

Resources