Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bindingContext.ModelName is empty?

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.

like image 748
Halo Avatar asked Jul 06 '12 21:07

Halo


1 Answers

I don't believe you need the bindingContext.ModelName property for what you are trying to do.

Going by Darin Dimitrov's answer, it looks like you can try the following. First you need a hidden field on your form for the type:

@using (Html.BeginForm("UrunEkle", "Yonetici")) {
    @Html.Hidden("UrunType", Model.Urun.GetType())

Then in your model binding (basically copied from Darin Dimitrov):

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
    var typeValue = bindingContext.ValueProvider.GetValue("UrunType");
    var type = Type.GetType(
        (string)typeValue.ConvertTo(typeof(string)),
        true
    );
    var model = Activator.CreateInstance(type);
    bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
    return model;
}

See this post for more info on how the bindingContext.ModelName is populated.

like image 196
Kevin Aenmey Avatar answered Sep 27 '22 17:09

Kevin Aenmey