In my application, I am trying to split the Date and Time from and DateTime field so I can put a jQuery date picker on the date. I found Hanselman\'s code for splitting the
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;
}
}
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.