Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data attributes on the AutocompleteFor html element #14

Open
stevenwoolston opened this issue May 14, 2017 · 1 comment
Open

Data attributes on the AutocompleteFor html element #14

stevenwoolston opened this issue May 14, 2017 · 1 comment

Comments

@stevenwoolston
Copy link
Contributor

The HtmlHelper that builds the dictionary, which is then used to populate the attributes of the resulting input, does not cater for data attributes to W3C standards. For example, there might be a use case to add a data attribute to the html element which is then used in the onselected method of the typeahead.mvc.model.js. This could be done, for example, to update another element on the form once the Autocomplete control is selected.

The convention in MVC views to add data attributes is to use the data_attributeName syntax using an underscore delimiter. If this is done, the AutocompleteFor HtmlHelper simply populates the data attribute in it's exact form on the html element - using the underscore. However, this is against W3C convention for data attributes.

I suggest that a change be made to the HtmlHelper to allow for data attributes. Here is a code block to do so (starting at line 86 of HtmlHelpers.cs)

var htmlAttributesPropertyNamesAndValues = pair.Value.GetType()
	.GetProperties()
	.Where(pi => pi.PropertyType == typeof (string) && pi.GetGetMethod() != null)
	.Select(pi => new
	{
		Name = pi.Name,
		Value = pi.GetGetMethod().Invoke(pair.Value, null)
	});
foreach (var pair2 in htmlAttributesPropertyNamesAndValues)
{
	var pair2Name = pair2.Name;
	if (pair2Name.Contains("data_"))
	{
		var dataAttributeName = pair2.Name.Replace("data_", "data-");
		pair2Name = dataAttributeName;
	}
	((IDictionary<string, object>) htmlAttributes).Add(pair2Name, pair2.Value);
}

At line 96, a variable is created to hold the value of the pair name. This value is checked to determine if is a data attribute. If so, replace the underscore accordingly and add the attribute to the dictionary object.

@timdwilson
Copy link
Owner

timdwilson commented May 15, 2017 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants