Mike
Mike

Reputation: 23

How to convert HtmlAttribute to string?

I want to convert HtmlAttribute to string in my custom HtmlHelper but convert isn't in correct format.

var attributes=new {@class="myClass" , id="elId"};
string convertedAttributes=attributes.ToString();
string myHtml="<input "+convertedAttributes+" />";
return new HtmlString(myHtml);

How can Id do that?

Upvotes: 2

Views: 181

Answers (1)

nsevens
nsevens

Reputation: 2835

The easiest would be using the System.Web.Mvc.TagBuilder class:

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

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

return tag.ToString();

Upvotes: 2

Related Questions