开发者

HtmlHelper and htmlAttributes help

开发者 https://www.devze.com 2023-03-16 01:06 出处:网络
I\'m f开发者_Go百科airly new to MVC 3 and am using the Razor view engine. I\'m using the Html.Hidden extension method to output input elements of type hidden. What I woudl also like to do is add a cus

I'm f开发者_Go百科airly new to MVC 3 and am using the Razor view engine. I'm using the Html.Hidden extension method to output input elements of type hidden. What I woudl also like to do is add a custom attribute to hold a dynamic value. I was under the impression in HTML5 wee could write custom html element attributes that are prefixed with 'data-'. I'm trying to do something like below;

@Html.Hidden("hdnID", mymodel.somevalue, new { data-uniqueid = mymodel.somevalue })

hoping to render;

<input type="hidden" value="mymodel.somevalue" data-uniqueid="mymodel.somevalue"/>

The htmlAttributes part (new { data-uniqueid = mymodel.somevalue }) is giving the error,

"Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access".

Can I add user-defined attribute to html elements using the HtmlHelper classes?

Regards,


Use:

@Html.Hidden("hdnID", mymodel.somevalue, new { @data_uniqueid = mymodel.somevalue })

The underscore gets automatically converted to a dash.


Doh! I was being silly. You can't have '-' in the anon type declaration:

data-uniqueid = ...it must be

datauniqueid = ....

In that case, your best best is to write out the hidden input by hand:

<input type="hidden" value="@mymodel.somevalue" data-uniqueid="@mymodel.somevalue"/>


You can step around the member validation by constructing a dictionary object. As follows:

@Html.TextBoxFor(model => model.Phone, new Dictionary<string, object>
{
    {
        "data-call-results-target", "#search-results-area" 
    },
    {
        "data-action-path", "/Controler/Method"
    }
})
0

精彩评论

暂无评论...
验证码 换一张
取 消