c# - Why does the model binder need an empty constructor -
i need some fundamentals here...
i have controller serves view instance of class (at least that's how think works). since giving view new instance of object, why have create newer 1 model binding post back? please @ below example.
[httpget] public actionresult index(){ int hi = 5; string temp = "yo"; mymodel foo = new mymodel(hi, temp); return view(foo); } [httppost] public actionresult index(mymodel foo){ mymodel poo = foo; if(poo.somestring == laaaa) return redircttoaction("end", "endcntrl", poo); else throw new exception(); } view: @model myapp.models.mymodel @html.editorfor(m => m.hi) <input type="submit" value="hit"/> model: public class mymodel { public int hi {get; set;} public string somestring {get; set;} public stuff(int number, string laaaa){ numberforclass = number; somestring = laaaa; } } why need blank constructor? furthermore, if had parameterless constructor, why poo.somestring change time got redircttoaction("end", "endcntrl", poo)?
why need blank constructor?
because of
[httppost] public actionresult index(mymodel foo){ ... } you asked binder give concrete instance on post, binder needs create object you. original object not persist between , post actions, (some of) properties live on html fields. thats "http stateless" means.
it becomes little more obvious when use lower level
[httppost] public actionresult index(formcollection collection) { var foo = new mymodel(); // load properties formcollection } why poo.somestring change time got
redircttoaction("end", "endcntrl", poo)?
because somestring isn't used in view. blank when new model back. change that:
@model myapp.models.mymodel @html.hiddenfor(m => m.somestring) @html.editorfor(m => m.hi) <input type="submit" value="hit"/> this store value hidden field in html , restored on post.
Comments
Post a Comment