Binding a string to a parameter using an implicit operator in ASP MVC

Though I am late, just for the sake of covering all available options: you could implement your own TypeConverter, as follows:

public class TitleConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string) ? true : base.CanConvertFrom(context, sourceType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        if (value is string)
            return new Title((string)value);

        return base.ConvertFrom(context, culture, value);
    }
}

[TypeConverter(typeof(TitleConverter))]
public class Title
{
    ...
}

This approach is especially useful if you need to instantiate your class from different types


As per you questions:

  1. The model binder is going to call new Title(). Which he can't. Then he would try to set a Title property. Which he can't find. No, the default binder does not call implicit conversions. The algorythm he uses is different.
  2. No, you don't need a custom binder, if you accept to change your Model, which is completely wrong in according to the behaviour of the default model binder.

The implicit conversion doesn't matter at all for Action binding.

The default model binder takes a big dictionary of values, gathered from the various parts of the request, and tries to insert them into properties.

So, if you want to use your Title as an Action parameter, your best bet is to make the Title class Binder-friendly, so to speak:

/* We call the class TitleModel in order not to clash
 * with the Title property.
 */
public class TitleModel
{
    public string Title { get; set; }

    /* If you really need the conversion for something else...
    public static implicit operator Title(string title)
    {
        return new Title { Title = title };
    }
    */
}

Everything should work as it is on the client side.

If you cannot (or don't want to) change your model class, then you can go for a custom model binder. But I don't think you really need it.

Tags:

C#

Asp.Net