ValueProvider does not contain a definition for TryGetValue

久未见 提交于 2019-12-01 15:48:54

TryGetValue() is not a member of System.Web.Mvc.IValueProvider. I suspect he has a custom extension which looks something like:

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

Update

TryGetValue() is not an extension method, but rather it is a method on the type IDictionary<T,U>. The type of bindingContext.ValueProvider has changed since MVC1 as @mootinator indicated. It's possible you can just ignore the call to TryGetValue() and instead call GetValue() and check the result for null. I'm not sure if it will throw an exception as I haven't tested it, so try that first.

I had this problem trying to follow Hanselman's example the other day. It's not an MVC2 example. TryGetValue doesn't work and/or isn't needed anymore. Try this link:

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

I created an MVC2 extension method from Hanselman's GetA method to replace, though I'm not sure whether it works as intended, since it didn't solve my unique problem, which didn't actually have anything to do with date or time.

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;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!