Как получить значения из объекта HtmlAttributes
В asp.net mvc я всегда вижу встроенные html-помощники, у них всегда есть объект htmlAttirbutes.
Затем я обычно делаю new {@id = "test", @class= "myClass" }.
Как извлечь такой параметр в мои собственные html-помощники?
Как я использую "HtmlTextWriterTag" - это способ, которым я могу передать весь этот объект писателю, и он понял это или что?
Также как это работает с большими html-помощниками?
Как я делаю html-помощник, и он использует все эти теги.
Table
thead
tfooter
tbody
tr
td
a
img
Означает ли это, что я должен сделать атрибут html для каждого из этих тегов?
Ответы
Ответ 1
Обычно я делаю что-то вроде этого:
public static string Label(this HtmlHelper htmlHelper, string forName, string labelText, object htmlAttributes)
{
return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
}
public static string Label(this HtmlHelper htmlHelper, string forName, string labelText,
IDictionary<string, object> htmlAttributes)
{
// Get the id
if (htmlAttributes.ContainsKey("Id"))
{
string id = htmlAttributes["Id"] as string;
}
TagBuilder tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("for", forName, true);
tagBuilder.SetInnerText(labelText);
return tagBuilder.ToString();
}
Я предлагаю вам загрузить источник ASP.NET MVC из кода и посмотреть на встроенные html-помощники.
Ответ 2
вы можете преобразовать объект htmlAttirbutes в представление строки атрибута/значения следующим образом:
var htmlAttributes = new { id="myid", @class="myclass" };
string string_htmlAttributes = "";
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
string_htmlAttributes += string.Format("{0}=\"{1}\" ", property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
}
PropertyDescriptor
относятся к классу System.ComponentModel
Ответ 3
Я использую сочетание обоих методов (Chtiwi Malek и rrejc), предложенное ранее, и оно отлично работает.
С помощью этого метода он преобразует data_id
в data-id
. Он также перезапишет значения атрибутов по умолчанию, которые вы установили ранее.
using System.ComponentModel;
...
public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
return MvcHtmlString.Empty;
var label = new TagBuilder("label");
label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes))
{
// By adding the 'true' as the third parameter, you can overwrite whatever default attribute you have set earlier.
label.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true);
}
label.InnerHtml = labelText;
return MvcHtmlString.Create(label.ToString());
}
Обратите внимание на комментарий о перезаписывании атрибута, который имеет значение по умолчанию в вашем коде в foreach.