pass data-icon attributes in razor html helper

若如初见. 提交于 2020-01-01 14:57:39

问题


I want to following html code using asp.net mvc 3 razor html helper:

<input type="text" .... .   placeholder="Login" data-icon="user" />

I have try this one:

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

or

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

Displayed Error:

Invalid anonymous type members declaration.

This might due to dash in data-icon not taken as attributes. How could I add data-icon attributes in text box field.


回答1:


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 :-)




回答2:


try this

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



回答3:


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" } })


来源:https://stackoverflow.com/questions/11603985/pass-data-icon-attributes-in-razor-html-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!