我不認爲你需要處理expandos將實現你的目標:
public static class HtmlExtensions
{
public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes)
{
var builder = new TagBuilder("div");
// define the custom attributes. Of course this dictionary
// could be dynamically built at runtime instead of statically
// initialized as in my example:
builder.MergeAttribute("data-myattribute1", "value1");
builder.MergeAttribute("data-myattribute2", "value2");
// now merge them with the user attributes
// (pass "true" if you want to overwrite existing attributes):
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes), false);
builder.SetInnerText("hello world");
return new HtmlString(builder.ToString());
}
}
,如果你想打電話現有的一些助手,那麼一個簡單的foreach循環可以做的工作:
public static class HtmlExtensions
{
public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes)
{
// define the custom attributes. Of course this dictionary
// could be dynamically built at runtime instead of statically
// initialized as in my example:
var myAttributes = new Dictionary<string, object>
{
{ "data-myattribute1", "value1" },
{ "data-myattribute2", "value2" }
};
var attributes = new RouteValueDictionary(htmlAttributes);
// now merge them with the user attributes
foreach (var item in attributes)
{
// remove this test if you want to overwrite existing keys
if (!myAttributes.ContainsKey(item.Key))
{
myAttributes[item.Key] = item.Value;
}
}
return htmlHelper.ActionLink("click me", "someaction", null, myAttributes);
}
}
您可以顯示助手的代碼?它會更好地說明你的目標。我懷疑你不需要任何ExpandoObject,並且可能有其他方法來實現你的目標。 –
@DarinDimitrov:是的,你是對的:)我用Dictionary :)解決了這個問題 –
xx77aBs
[Cast ExpandoObject to anonymous type]可能重複(http://stackoverflow.com/questions/10241776/cast- expandoobject-to-anonymous-type) – nawfal