2017-03-06 41 views
0

我尝试marging 2匿名对象和结果传递给urlHelper.action()方法,但结果是错误的,.NET MVC和url.Action与marging匿名

这是我的代码:

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; 

}

什么是错的,我aspected像到HREF变量: “... /修改/ 123 = RETURNURL ......”

谢谢 问候

+0

为什么你使用'dynamic'?只需使用'new RouteValueDictionary(routeValues)'和使用'.Add()'方法创建'RouteValueDictionary'以添加其他键/值对 –

+0

因为这是我的buttonhelper扩展的剪切代码,item1源处于我的cshtml代码,我不知道包含什么 –

+0

你是什么意思,你不知道它包含什么? - 你已经分配给'string returnUrl',但为什么你使用'@ Html.EditButton(new {returnUrl = ViewBag.returnUrl,},“xxx”)'? –

回答

0

好吧,我解决我修改玛吉方法新的代码是:

 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; 
}