tags:

views:

10

answers:

1

Basically I'm looking for the best way to remove the need to hard code any actual URLs within views when two different URLs call the same controller action. As shown below, two routes define different URLs, one for creating a new customer, whilst the other is for editing an existing customer. Inside the controller action it determines what to do by checking the value of AccountNumber - if it was not provided (null) then it knows that it is creating a new customer.

routes.MapRoute("Customer_Edit", "Customer/Edit/{CustNum}", new { controller = "Customer", action = "Edit", AccountNumber = "{CustNum}" });
routes.MapRoute("Customer_Create", "Customer/Create", new { controller = "Customer", action = "Edit" });

The downside to this approach is that you can't use Url.Action(...) in the views to determine the URL because there are two different URLs mapping to the controller action. I had hoped that the call to Url.Action(...) would determine which to use by the "RouteValues" provided, but it just appears to use the 1st matching route defined. So in this case if you call Url.Action("Edit", "Customer", new {CustNum = 2}) you get "Customer/Edit/2" as you'd expect, but if you call Url.Action("Edit", "Customer") the view outputs the URL "Customer/Edit/{CustNum}".

Is there anyway using this configuration that you would not need to hard code URLs into the view? Or is it considered better practise to have a separate action for creating new customers and another action for editing customers, so you end up with the following

public class CustomerController : Controller
{
     public ActionResult Create()
     { return CreateOrEdit(null); }

     public ActionResult Edit(int custNum)
     { return CreateOrEdit(custNum); }

     private ActionResult CreateOrEdit(int? custNum)
     {....}
}
+1  A: 

Use Url.RouteUrl instead and specify the route you want. In addition to actually working, RouteUrl is on the order of 10* faster than Action.

Craig Stuntz
Thanks, that does exactly what was needed. Cheers also for the performance tip.
Paul Hadfield