The code I have to implement takes a posted list of data from an Ajax call from a web page.
I know the object I need to update, but each field/value pair is coming through as string values and not as their proper types.
So I am trying to work out the type of the property, casting the value as the new type and then apply that to the field using reflection.
However I am getting the following error for anything other than strings.
Invalid cast from 'System.String' to 'System.TimeSpan'.
The code I am attempting the conversion in is;
public void Update<T>(string fieldName, string fieldValue)
{
System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
Type propertyType = propertyInfo.PropertyType;
var a = Convert.ChangeType(fieldValue, propertyType);
}
So is the target object.
There is no absolute answer that works for all types. But, you could use a TypeConverter instead of Convert, it usually works better. For example, there is a TimeSpanConverter:
public void Update<T>(string fieldName, string fieldValue)
{
System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
Type propertyType = propertyInfo.PropertyType;
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(typeof(string)))
{
var a = converter.ConvertFrom(fieldValue, type);
...
}
}
For handling JSON in MVC (and .NET in general) I use JSON.NET. It is included out-of-the-box in the ASP.NET MVC 4 project template and available on NuGet otherwise. Deserializing JSON string content is (generally) as simple as:
JsonConvert.DeserializeObject<Customer>(json);
If the JSON being passed isn't a serialized model, you could create a code model to match the JSON.
If that doesn't work for your scenario, you can try the Convert
class which has options for conversion if you know the type:
Convert.ToInt32(stringValue);
Or the ChangeType
method if it's dynamic:
Convert.ChangeType(value, conversionType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With