0

Just wondering if anyone can help me.

I have an MVC project and in my view I'm using url.action to link to my action. My action can handle 3 optional parameters Category, SubCategory and a Name. But the problem is SubCategory could be Null so I need Name to replace Subcategory in the URL.Action link. I have my code working but I'm wondering if there is a better way of writing this code.

My URL.Action:

if(subcategory == null)
{
    <a href="@Url.Action("Action", "Controller", new { Parameter1 = Category, Parameter2 = subcategory, DataParameter3 = name})">Products</a>
}
else
    <a href="@Url.Action("Action", "Controller", new { Parameter1 = Category, Parameter2 = name})">Products</a>

Does any one know a better way of doing this??

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
  • instead of a generic parameter I name the fields on the controller and in the case where name is null I just test for that on the controller and handle it accordingly – Matt Bodily Feb 13 '14 at 16:31
  • you can handle on the controller level and can redirect to another action based on the paramters – Sunny Feb 13 '14 at 16:35

2 Answers2

0

Not sure this is much better, but it seems cleaner in my mind at least...

@functions{
 IDictionary<string, object> GetRouteValues()
 {
    var vals = new Dictionary<string, object>();
    vals.Add("Parameter1", Category);
    if (subcategory != null){ 
      vals.Add("Parameter2", subcategory);
      vals.Add("Paremeter3", name);
    } else {
      vals.Add("Parameter2", name);
    }
    return vals;
 }
}

@Html.ActionLink("Products", "Action", "Controller", GetRouteValues(), null)
James S
  • 3,558
  • 16
  • 25
0

It is other way to write <a> link once. Firstly, check subcategory is null or not:

@{
   string Parameter2 = name;
   string DataParameter3 = name;
   if(subcategory == null) Parameter2 = subcategory; else Parameter3 = null;
 }

<a href="@Url.Action("Action", "Controller", new { Parameter1 = Category, Parameter2 = Parameter2 , DataParameter3 = DataParameter3 })">Products</a>

And your action may be like this:

public ActionResult Action(Parameter1, Parameter2, DataParameter3 = null )
{
}
Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90