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.
我有一个MVC项目,在我看来我正在使用url.action链接到我的动作。我的动作可以处理3个可选参数Category,SubCategory和Name。但问题是SubCategory可能是Null所以我需要Name来替换URL.Action链接中的Subcategory。我的代码工作正常,但我想知道是否有更好的方法来编写这段代码。
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??
有人知道更好的方法吗?
2 个解决方案
#1
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)
#2
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 )
{
}
#1
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)
#2
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 )
{
}