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??

4

2 回答 2

0

不确定这会好得多,但至少在我看来它看起来更干净......

@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)
于 2014-02-13T16:45:44.930 回答
0

这是写<a>一次链接的另一种方式。首先,检查是否subcategory为空:

@{
   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>

而你的动作可能是这样的:

public ActionResult Action(Parameter1, Parameter2, DataParameter3 = null )
{
}
于 2014-02-14T12:41:08.737 回答