MVC动态routeValues​​为ActionLinks [英] MVC dynamic routeValues for ActionLinks

查看:190
本文介绍了MVC动态routeValues​​为ActionLinks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要使用ActionLink的链接到安编辑屏幕为我的ViewModel一个。

I have a need to use ActionLink to link to ann edit screen for my ViewModel A.

一个具有复合键,所以要链接到它的路由值必须有3 pramaters,像这样的:

A has a composite key, so to link to it, the route values will have to have 3 pramaters, like this:

<%: Html.ActionLink("EDIT", "Action", "Controller", 
    new { area = "Admin", Id1= 1, Id2= 2, Id3= 3 })%>

如你所见,路线值包含的ID控制器的行动将接受的。

As you can see, the route values contain the ids that the controller Action will accept.

我希望能够从一个辅助函数生成路由值,如:

I want to be able to generate the route values from a helper function, like this:

public static Object GetRouteValuesForA(A objectA)
    {
        return new
        {
            long Id1= objectA.Id1,
            long Id2= objectA.Id2,
            long Id3= objectA.Id3
        };
    }

,然后使用它在ActionLink的帮手,但我不知道如何该结果传递给ActionHelper

And then use it in the ActionLink helper, but I don't know how to pass that result to the ActionHelper

objectA = new A(){Id1= objectA.Id1,Id2= objectA.Id2,Id3= objectA.Id3};
....
<%: Html.ActionLink("EDIT", "Action", "Controller", 
    new { area = "Admin", GetRouteValuesForA(objectA) })%>

但是,这需要控制器动作接受匿名类型,而不是3属性列表

But that would need the controller action to accept that anonymous type instead of a list of 3 properties

我看到了下面的链接,合并匿名类型,但是否有任何其他方式做到这一点?
合并匿名类型

I saw the below link that merges anonymous type, but is there any other way to do this? 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())%>

您现在可以重新使用它们,就像你喜欢的,只有曾经有改变他们在一个地方。

You can now reuse them as much as you like and only ever have to change them in one place.

这篇关于MVC动态routeValues​​为ActionLinks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆