Asp.net mvc 如何将HtmlAttribute转换为字符串?

Asp.net mvc 如何将HtmlAttribute转换为字符串?,asp.net-mvc,Asp.net Mvc,我想将HtmlAttribute转换为自定义HtmlHelper中的字符串,但转换格式不正确 var attributes=new {@class="myClass" , id="elId"}; string convertedAttributes=attributes.ToString(); string myHtml="<input "+convertedAttributes+" />"; return new HtmlString(myHtml); var attribute

我想将HtmlAttribute转换为自定义HtmlHelper中的字符串,但转换格式不正确

var attributes=new {@class="myClass" , id="elId"};
string convertedAttributes=attributes.ToString();
string myHtml="<input "+convertedAttributes+" />";
return new HtmlString(myHtml);
var attributes=new{@class=“myClass”,id=“elId”};
string convertedAttributes=attributes.ToString();
字符串myHtml=“”;
返回新的HtmlString(myHtml);

Id如何做到这一点?

最简单的方法是使用
System.Web.Mvc.TagBuilder
类:

var attributes = new { @class = "myClass", id = "elId" };

var tag = new TagBuilder("input");
tag.MergeAttributes(new RouteValueDictionary(attributes));

return tag.ToString();
试试@Html.Raw(字符串)