2

When I pass a model to my View in a form, the fields are pre-populated with default values, especially if the model property is an int data type, is there anyway to prevent this?

For example:

Model:

public class MyModel {
    [Key]
    public int MyKey { get; set; }
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

Controller:

public class MyController : Controller {
    public ActionResult MyAction(int id) {
        return View(context.MyModel.Single(x=>x.MyKey == id));
    }
}

View:

@model MyNamespace.MyModel

@using(Html.BeginForm())
{
    @Html.HiddenFor(x=>x.MyKey)
    @Html.EditorFor(x=>x.MyInt)
    @Html.EditorFor(x=>x.MyString)
    <input type="submit" value="Submit />
}

In the view, the input field for MyInt will be pre-populated with 0 whereas the MyString input will be empty. I want MyInt to be empty too.

Edit:

To clarify, I just wish for the input field to be empty when the page loads and not contain its default value of 0

1 Answer 1

4

Use int? instead of int whitch allows you to keep empty values in the inputs.

P.S. Here is related question but with DateTime type: Setting default values for a Model in MVC3

Sign up to request clarification or add additional context in comments.

1 Comment

Oh wow, its that easy, thanks for your answer, i'll mark it as the answer when i'm able too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.