如何将@readonly = readonly添加到现有的additionalViewData属性中?

时间:2015-02-12 20:41:19

标签: c# asp.net-mvc-5

我做这样的事情:

public static MvcHtmlString DimensionEditorFor<TModel, TValue>(this HtmlHelper<TModel> a_html, Expression<Func<TModel, TValue>> a_expression, DimensionLock a_lock, object a_additionalViewData)
{
    var dictionary = new RouteValueDictionary(a_additionalViewData);

    if (a_lock.IsLocked)
    {
        object htmlAttributes;
        if (dictionary.TryGetValue("htmlAttributes", out htmlAttributes))
        {
            var htmlAttributesDict = new RouteValueDictionary(htmlAttributes);
            htmlAttributesDict["@readonly"] = "readonly";
            htmlAttributes = htmlAttributesDict;
        }
        else
        {
            htmlAttributes = new {@readonly = "readonly"};
        }

        dictionary["htmlAttributes"] = htmlAttributes;
    }

    return a_html.EditorFor(a_expression, dictionary);
}

这不起作用,因为RouteValueDictionary对象在additionalViewData扩展方法中不是EditorFor的允许值。如果a_lock.IsLocked为真,我想在渲染文本框上设置只读。

更新

我尝试了以下内容,看看ViewDataDictionary是否可行。它没有。

public static MvcHtmlString DimensionEditorFor<TModel, TValue>(this HtmlHelper<TModel> a_html, Expression<Func<TModel, TValue>> a_expression, DimensionLock a_lock, object a_additionalViewData)
{
    var dictionary = new ViewDataDictionary();
    foreach (KeyValuePair<string, object> pair in new RouteValueDictionary(a_additionalViewData))
        dictionary.Add(pair.Key, pair.Value);

    return a_html.EditorFor(a_expression, dictionary);
}

1 个答案:

答案 0 :(得分:0)

它并不完全优雅,但如果您需要的只是对象是ViewDataDictionary而不是RouteValueDictionary。你可以随时做:

var viewData = new ViewDataDictionary();
foreach (var key in dictionary.Keys)
{
    viewData[key] = dictionary[key];
}