MVC form is (unintendedly) populated on http get

262 Views Asked by At

It seems that there's some fundamental MVC part I don't get. Here's the situation:

I have View (Index.aspx) with three partial views (one with a table, two with one form each).

All four views are strongly typed; the parent (index.aspx) has a model that contains three Properties that are passed as models to the partial views.

One of the Models for one of the partial views (a form that allows a user to create a new record for the table) has DataAnnotations in order to enable validation when the form is submitted. Two form fields are integers with a RangeAttribute [Range(1000,9999)] and two are DateTime with a DisplayFormatAttribute like [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}")]

My partial views use the Html.EditorFor() helper for the input fields like so:

<%: Html.EditorFor<MyType, DateTime>(m => m.StartDate, new { @class = "specialclass" })%>

In my Action method I create a View model for my parent and also add empty view models for the partials (except the table which is populated with records), I then pass that to my return View() statement. I excepted that the table would be populated, but the form fields should be empty, but they are not.

So, why are my form fields populated with 0 for the two integer fields and the minimum date value for the two date fields when I do a HTTP get for the view?

What am I doing wrong/what am I not getting?

I guess my question is: if I have a strongly typed user control which is a form, how should that be "treated" when I do a http get for the parent view? I need to pass it a model, right?

1

There are 1 best solutions below

1
On

Whether you set the values or not, the system is going to try to present them. As int isn't nullable it tends to return 0 when uninitialised so that one is clear. The DateTime I'm assuming, because it would be null, is defaulting to the DateTime.Min as you have specified that you expect there to be data both through the field and the formatting.