pass data-icon attributes in razor html helper

2019-04-12 04:37发布

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.

3条回答
迷人小祖宗
2楼-- · 2019-04-12 04:59

try this

@Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", data_icon = "user" })
查看更多
趁早两清
3楼-- · 2019-04-12 05:04

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

查看更多
等我变得足够好
4楼-- · 2019-04-12 05:07

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" } })
查看更多
登录 后发表回答