أساليب HtmlHelper وRouteValueDictionary
-
22-08-2019 - |
سؤال
عند كتابة ملحق htmlhelper، إذا كنت أرغب في دعم العناصر ذات البنية المشابهة لطريقة ملحق htmlhelper الخاصة بي، فإنني أستخدمها RouteValueDictionary
على النحو التالي:
public static string ListBoxDict(this HtmlHelper htmlHelper,
string name,
object value,
object htmlAttributes)
{
return ListBoxDict(htmlHelper,
name,
value,
((IDictionary<string, object>)
new RouteValueDictionary(htmlAttributes)));
}
سؤالي حقا هو لماذا الحاجة ل RouteValueDictionary
...أعلم أنك لا تستطيع أن تلقي فقط htmlAttributes
ل IDictionary<string, object>
...على الرغم من أنني لست متأكدًا من السبب، وقد يكون هذا هو المكان الذي أشعر فيه بالحيرة.لا ينبغي RouteValueDictionary
هل له علاقة بالتوجيه وبالتالي لا علاقة له بأساليب HtmlHelper؟كما قلت، ربما أفتقد النقطة، لذا سأكون سعيدًا إذا أخبرني شخص ما بما فاتني.
هتافات...
يحرر:ردًا على إجابة دان -->
كنت أتابع فقط ما رأيته قيد الاستخدام في كود مصدر mvc لمساعدي الإدخال ...
- يرى "
src\SystemWebMvc\Mvc\Html\InputExtensions.cs
"
يفعل كما يلي:
public static string TextBox(this HtmlHelper htmlHelper,
string name,
object value,
object htmlAttributes)
{
return TextBox(htmlHelper,
name,
value,
new RouteValueDictionary(htmlAttributes))
}
من الواضح أنه اختصار ولكن هل هو غش أم أنه من المقبول القيام بذلك؟
المحلول
أوصي بشدة بالنظر إلى Rob Conery's مشاركة مدونة عن شيء مثل هذا.
اللحوم والخضار هي كالتالي:
تفريغ الكود:
public static string ToAttributeList(this object list)
{
StringBuilder sb = new StringBuilder();
if (list != null)
{
Hashtable attributeHash = GetPropertyHash(list);
string resultFormat = "{0}=\"{1}\" ";
foreach (string attribute in attributeHash.Keys)
{
sb.AppendFormat(resultFormat, attribute.Replace("_", ""),
attributeHash[attribute]);
}
}
return sb.ToString();
}
public static string ToAttributeList(this object list,
params object[] ignoreList)
{
Hashtable attributeHash = GetPropertyHash(list);
string resultFormat = "{0}=\"{1}\" ";
StringBuilder sb = new StringBuilder();
foreach (string attribute in attributeHash.Keys)
{
if (!ignoreList.Contains(attribute))
{
sb.AppendFormat(resultFormat, attribute,
attributeHash[attribute]);
}
}
return sb.ToString();
}
public static Hashtable GetPropertyHash(object properties)
{
Hashtable values = null;
if (properties != null)
{
values = new Hashtable();
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(properties);
foreach (PropertyDescriptor prop in props)
{
values.Add(prop.Name, prop.GetValue(properties));
}
}
return values;
}
الاستخدام:
public static string ListBoxDict(this HtmlHelper htmlHelper,
string name,
object value,
object htmlAttributes)
{
return htmlHelper.ListBoxDict(name,
value,
htmlAttributes.ToAttributeList()));
}
ماذا .ToAttributeList()
ما يفعله هو تحويل كائن htmlAttribute إلى
الاسم = "القيمة"
نأمل أن يكون هذا منطقيا.