2017-06-02 112 views
0

是将字符串(此字符串可以更改并包含asp-route -...属性)转换为html属性列表的方式吗?剃刀引擎应该使用所有的asp-route -...属性来转换为正确的url。我有以下代码,但不起作用。将字符串转换为html属性

@{ 
    var Attributes  = ViewData["Attributes"] as Dictionary<string,string>; 
    var AttributeRoute = ""; 

    @foreach (var key in Attributes.Keys) 
    { 
     AttributeRoute += "asp-route-"+key+"=\""+Attributes[key]+"\" "; 
    } 
} 

... 

@AttributeRoute #Prints output (ex. asp-route-testkey="testvalue") 

<a class='item' @AttributeRoute>test</a> #Doesn't print the list of attributes 

回答

0

通过以下操作解决了它自己:

1.创建自定义Taghelper类

namespace test 
{ 
    [HtmlTargetElement("special-link")] 
    public class SpecialLinkTagHelper : TagHelper 
    { 
     [ViewContext] 
     public ViewContext ViewContext { get; set; } 

     public override void Process(TagHelperContext context, TagHelperOutput output) 
     { 
      //Create a tag 
      output.TagName="a"; 

      //Get the parameters 
      string parameters=""; 
      Dictionary<string,string> Parameters = (Dictionary<string,string>)this.ViewContext.ViewData["Attributes"]; 
      foreach(KeyValuePair<string, string> pair in Parameters){ 
       parameters+= pair.Key+"="+pair.Value+"&"; 
      } 

      output.Attributes.SetAttribute("href", "?"+parameters); 
     } 
    } 
} 

2.创建链接(在.cshtml文件)

<special-link>link</special-link> 

希望这可以帮助别人!