ValueProvider不包含TryGetValue的定义。

9
在我的应用程序中,我正在尝试从DateTime字段中拆分日期和时间,以便我可以在日期上放置jQuery日期选择器。我发现Hanselman's code for splitting the DateTime,但我得到了一个编译错误“bindingContext.ValueProvider.TryGetValue(modelName, out valueResult);”。我得到的错误是:“'System.Web.Mvc.IValueProvider'不包含对'TryGetValue'的定义,也找不到接受类型为'System.Web.Mvc.IValueProvider'的第一个参数的扩展方法'TryGetValue'(是否丢失使用指令或程序集引用?)”我错过了什么吗?我创建了一个新类,并将他的代码放在我的项目中的Helpers文件夹中。

我们能否将标题更改为更准确的内容?例如:“IValueProvider不包含TryGetValue的定义”之类的?我可以更改吗?这将有助于其他人通过准确的问题描述找到您的问题。 - jcolebrand
2个回答

14

TryGetValue()不是System.Web.Mvc.IValueProvider的成员。我怀疑他有一个自定义扩展程序,看起来像这样:

public static bool TryGetValue(this IValueProvider valueProvider, string key, out ValueProviderResult result) {
    try {
        result = valueProvider.GetValue(key);
        return true;
    }
    catch {
        result = null;
        return false;
    }
}

更新

TryGetValue() 不是扩展方法,而是 IDictionary<T,U> 类型上的方法。正如 @mootinator 所指出的那样,bindingContext.ValueProvider 的类型自 MVC1 以来已经发生了变化。你可以尝试忽略对 TryGetValue() 方法的调用,转而调用 GetValue() 方法并检查结果是否为 null。我不确定它是否会抛出异常,因为我还没有测试过,请先尝试这种方法。


4
确认新的GetValue()方法如未在绑定上下文中找到键,则返回null,因此不再需要try/catch语句。 - Xavier Poinas

6

我曾经遇到过这个问题,试图按照Hanselman的示例操作。但那不是一个MVC2的示例。现在已经不需要使用TryGetValue了。请尝试访问这个链接:

http://forums.asp.net/p/1529895/3706154.aspx

我从Hanselman的GetA方法创建了一个MVC2扩展方法来替换,尽管我不确定它是否按预期工作,因为它没有解决我的独特问题,这实际上与日期或时间无关。
public static T? GetA<T>(this ModelBindingContext bindingContext, string key) where T : struct
        {
            T? valueResult = null;
            if (String.IsNullOrEmpty(key)) return null;
            //Try it with the prefix...
            try
            {
                valueResult = (T?)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + key).ConvertTo(typeof (T));
            } catch (NullReferenceException){}
            //Didn't work? Try without the prefix if needed...
            if (valueResult == null && bindingContext.FallbackToEmptyPrefix == true)
            {
                try
                {
                    valueResult = (T?) bindingContext.ValueProvider.GetValue(key).ConvertTo(typeof (T));
                } catch (NullReferenceException){}
            }
            return valueResult;
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接