c# - bindingContext.ModelName is empty? -


so i'm trying apply darin dimitrov's answer, in implementation bindingcontext.modelname equal "".

here's viewmodel:

public class urunviewmodel { public urun urun { get; set; } public type uruntype { get; set; } } 

here's part of view posts 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 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, line in global.asax.cs:

modelbinders.binders.add(typeof(urunviewmodel), new urunbinder()); 

here inside overridden createmodel function, in debugging mode can see bindingcontext.modelname equal "". , also, typevalue null createinstance function fails.

i don't believe need bindingcontext.modelname property trying do.

going darin dimitrov's answer, looks can try following. first need hidden field on form type:

@using (html.beginform("urunekle", "yonetici")) { @html.hidden("uruntype", model.urun.gettype()) 

then in model binding (basically copied 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 more info on how bindingcontext.modelname populated.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

c++ - Accessing inactive union member and undefined behavior? -

php - Get uncommon values from two or more arrays -