asp.net mvc - How to set default value to empty EditorFor-field when post a form i .NET MVC -
i have form in .net mvc 5. user can write number, default "0", if user deletes number e.g. "233" leaving field empty. form not submit.
how can submit form empty field?
public class mymodel { public int nummer { get; set; } public mymodel(){} public mymodel(int i) {this.nummer = i;} }
razor code:
using (html.beginform("myaction", "mycontroller", formmethod.post, new { @class = "form-inline" })) { @html.antiforgerytoken() @html.validationsummary(true, "", new { @class = "text- danger" }) @html.editorfor(model => model.nummer, new { htmlattributes = new { @class = "form-control " } }) <input type="submit" value="submit" name="btnsubmit"/> }
i not interested in validation error message, have value set "0", default.
the defaultmodelbinder
initializes model using parameterless constructor (your second constructor never called). need make property nullable prevent client , server side validation errors
public int? nummer { get; set; }
and in post method, test null , if so, set value 0
if(!model.nummer.hasvalue) { model.nummer = 0; }
alternatively write own modelbinder
tests null
value , in modelbinder
, set value 0
Comments
Post a Comment