我需要使用 ActionLink 链接到我的 ViewModel A 的编辑屏幕。
A 有一个复合键,所以要链接到它,路由值必须有 3 个参数,如下所示:
<%: Html.ActionLink("EDIT", "Action", "Controller",
new { area = "Admin", Id1= 1, Id2= 2, Id3= 3 })%>
如您所见,路由值包含 Controller Action 将接受的 ID。
我希望能够从辅助函数生成路由值,如下所示:
public static Object GetRouteValuesForA(A objectA)
{
return new
{
long Id1= objectA.Id1,
long Id2= objectA.Id2,
long Id3= objectA.Id3
};
}
然后在 ActionLink 助手中使用它,但我不知道如何将该结果传递给 ActionHelper
objectA = new A(){Id1= objectA.Id1,Id2= objectA.Id2,Id3= objectA.Id3};
....
<%: Html.ActionLink("EDIT", "Action", "Controller",
new { area = "Admin", GetRouteValuesForA(objectA) })%>
但这需要 Controller 操作来接受匿名类型而不是 3 个属性的列表
我看到下面的链接合并了匿名类型,但是有没有其他方法可以做到这一点? Merging anonymous types
最佳答案
这样的事情怎么样?
型号:
public class AViewModel
{
public string Id1 { get; set; }
public string Id2 { get; set; }
public string Id3 { get; set; }
public RouteValueDictionary GetRouteValues()
{
return new RouteValueDictionary( new {
Id1 = !String.IsNullOrEmpty(Id1) ? Id1 : String.Empty,
Id2 = !String.IsNullOrEmpty(Id2) ? Id2 : String.Empty,
Id3 = !String.IsNullOrEmpty(Id3) ? Id3 : String.Empty
});
}
}
查看:
<%: Html.ActionLink("EDIT", "Action", "Controller", Model.GetRouteValues())%>
您现在可以随心所欲地重复使用它们,而且只需在一个地方更改它们。
关于c# - ActionLinks 的 MVC 动态路由值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13533778/