.net MVC和url.Action与匿名游戏

时间:2017-03-06 10:26:04

标签: c# .net asp.net-mvc

我尝试使用2个匿名对象并将结果传递给urlHelper.action()方法,但结果是错误的,

这是我的代码:

public static MvcHtmlString EditButton(this HtmlHelper helper, object routeValues = null, string text = "")
    {
        UrlHelper u = new UrlHelper(helper.ViewContext.RequestContext);

        routeValues = routeValues ?? new { };

        string returnUrl = (string)helper.ViewBag.returnUrl;

        if (false == string.IsNullOrEmpty(returnUrl))
            routeValues = ButtonHelper.Merge(routeValues, new { returnUrl = returnUrl });

        var x = u.RouteUrl(new RouteValueDictionary(routeValues));
        string href = u.Action("Edit",new RouteValueDictionary(routeValues));//<--here I aspect that href=".../edit/123?returnUrl=...."
        text = string.IsNullOrEmpty(text) ? Resources.Commons.Edit : text;

        //        < a href = '@Url.Action("Edit", new { id = Model.Id })' class="btn btn-default">
        //    <i class="glyphicon glyphicon-pencil"></i> @Resources.Commons.Edit
        //</a>
        MvcHtmlString r = new MvcHtmlString(String.Format("<a href=\"{0}\" class=\"btn btn-default\">"
            + "<i class=\"glyphicon glyphicon-pencil\"></i> {1}</a>", href, text));
        return r;
    }

    public static dynamic Merge(dynamic item1, dynamic item2)
    {
        var result = new ExpandoObject();
        var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary

        foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties())
        {
            d[fi.Name] = fi.GetValue(item1, null);

        }
        foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties())
        {
            d[fi.Name] = fi.GetValue(item2, null);

        }

        return d;

}

出了什么问题,我认为href变量喜欢:&#34; ... / edit / 123?returnUrl = ....&#34;

谢谢 此致

1 个答案:

答案 0 :(得分:0)

好的我解决了我修改Marge方法的新代码是:

        public static RouteValueDictionary Merge(dynamic item1, dynamic item2)
        {
            var result = new ExpandoObject();
            var d = new RouteValueDictionary();

            foreach (System.Reflection.PropertyInfo fi in item1.GetType().GetProperties())
            {
                d[fi.Name] = fi.GetValue(item1, null);

            }
            foreach (System.Reflection.PropertyInfo fi in item2.GetType().GetProperties())
            {
                d[fi.Name] = fi.GetValue(item2, null);

            }

            return d;
}