So I'm trying to apply Darin Dimitrov's answer, but in my implementation bindingContext.ModelName is equal to "".
Here's my viewmodel:
public class UrunViewModel
{
public Urun Urun { get; set; }
public Type UrunType { get; set; }
}
Here's the part of the view that posts the model types:
@model UrunViewModel
@{
ViewBag.Title = "Tablo Ekle";
var types = new List<Tuple<string, Type>>();
types.Add(new Tuple<string, Type>("Tuval Baskı", typeof(TuvalBaski)));
types.Add(new Tuple<string, Type>("Yağlı Boya", typeof(YagliBoya)));
}
<h2>Tablo Ekle</h2>
@using (Html.BeginForm("UrunEkle", "Yonetici")) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Tablo</legend>
@Html.DropDownListFor(m => m.UrunType, new SelectList(types, "Item2", "Item1" ))
And here's my custom model binder:
public class UrunBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type type)
{
var typeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Urun");
var model = Activator.CreateInstance((Type)typeValue.ConvertTo(typeof(Type)));
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
return model;
}
}
Finally, the line in Global.asax.cs:
ModelBinders.Binders.Add(typeof(UrunViewModel), new UrunBinder());
Here inside the overridden CreateModel
function, in debugging mode I can see that bindingContext.ModelName
is equal to "". And also, typeValue
is null so CreateInstance
function fails.