How to set default value to empty EditorFor-field when post a form i .NET MVC

I have a form in .NET MVC 5. where the user can write a number, default is "0", If the user deletes a number e.g. "233" an leaving the field empty. The form would not submit.

How can I submit the form with an 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 am not interested in a validation error message, but to have the value set to "0", by default.

Upvotes: 3

Views: 4430

Answers (3)

user3559349
user3559349

Reputation:

The DefaultModelBinder initializes your model using the parameterless constructor (your second constructor is never called). You will need to make the property nullable to prevent client and server side validation errors

public int? nummer { get; set; }

and then in the POST method, test for null and if so, set the value to 0

if(!model.nummer.HasValue)
{
    model.nummer = 0;
}

Alternatively you could write your own ModelBinder that tests for a null value and in the ModelBinder, set the value to 0

Upvotes: 3

Joseph Woodward
Joseph Woodward

Reputation: 9281

You will need to set your nummer field to be a nullable type, like so:

public class myModel 
{
    public int? nummer { get; set; }
    ...
}

This will allow a user to submit the form without a value entered.

Then within your controller action you will need to assign a default value if the field is null:

if (model.nummer == null) model.nummer = 0;

Alternatively, you could use a private property like so:

public class myModel 
{
    private int? privateNummer { get; set; }

    public int? nummer
    {
        get { return this.privateNummer == null ? 0 : this.privateNummer; }
        set
        {
            this.privateNummer = value;
        }
    }
}

Upvotes: 1

REDEVI_
REDEVI_

Reputation: 684

in your controller before passing the model back to the view do this ..

    model.find(id);
    model.nummer =0;

    return View(model)

Upvotes: 0

Related Questions