pass data-icon attributes in razor html helper

点点圈 提交于 2019-12-04 14:28:20

Yes, you can't write like that but you can write your own Extension to solve this problem. Here is the sample code:

public static MvcHtmlString MyInput(this HtmlHelper htmlHelper, string name, string value, string icon)
    {
        var attrs = new Dictionary<string,object>();
        attrs.Add("data-icon", icon);
        return htmlHelper.TextBox(name, name, value, attrs);
    }

Or you can also use in razor like this:

@{
    var attrs = new Dictionary<string, object>();
    attrs.Add("placeholder","Login"); 
    attrs.Add("data-icon","user");
}
@Html.TextBoxFor(m => m.UserName, attrs)

Plz don't forget to mark it's right answer if it helps you :-)

try this

@Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", data_icon = "user" })

This is really the same as vNext's second alternative, but if you prefer to write it in-line:

@Html.TextBoxFor(m => m.UserName, new Dictionary<string, object> { { "placeholder", "Login" }, { "data-icon", "user" } })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!