asp.net mvc 2 - Simple Model Binding Not Working For Integer -
i'm trying figure out why simple controller action isn't working. i'm trying increase number
after every post.
model
public class viewmodel { public int number { get; set; } }
view
<body> <% using (html.beginform("test", "invoice")) { %> <%: html.editorfor(m => m.number) %> <%= model.number %> <input type="submit" value="submit" /> <% } %> </body>
controller
public actionresult test() { var viewmodel = new viewmodel {number = 1}; return view("test", viewmodel); } [httppost] public actionresult test(viewmodel viewmodel) { viewmodel.number = viewmodel.number + 1; return view("test", viewmodel); }
in controller, viewmodel.number
increased 2
, when view returned text box contains 1
, model.number
displays 2.
am missing something?
the html helpers favor values in modelstate
on actual model values.
so if modify model in action need clear modelsate
before passing view:
[httppost] public actionresult test(viewmodel viewmodel) { viewmodel.number = viewmodel.number + 1; modelstate.clear(); return view("test", viewmodel); }
you can read more asp.net mvc feature in great article:
asp.net mvc postbacks , htmlhelper controls ignoring model changes
Comments
Post a Comment