Ajax form always posting ViewModel with null values (MVC 4)

Whenever I submit the form, the ViewModel object in the controller action has null (or default) values for every field in the ViewModel. The ViewModel object itself isn’t null, but all of its values are null or default (0 for the ints, 1/1/0001 12:00:00 AM for the DateTimes, etc.).

After Googling this issue and seeing various suggestions, I’ve confirmed the following:

  • The model state is valid.
  • The names in the HTML markup for each field exactly match the name of the parameter in the ViewModel (NewItem.ID, NewItem.AnotherID, etc.).
  • Changing the name of the parameter has no effect.

Why aren’t the ViewModel values posting correctly?

Here’s what I have:

PaneViewModel

public class PaneViewModel
{
    public ViewModel NewItem { get; set; }
    public DataTableViewModel DataTable { get; set; }
}

ViewModel

[Table("TableName")]
public class ViewModel
{
    [Key]
    [Column(Order = 0)]
    [DisplayName("ID")]
    public int ID { get; set; }

    [Key]
    [Column(Order = 1)]
    [DisplayName("AnotherID")]
    public int AnotherID { get; set; }

    [Key]
    [Column(Order = 2)]
    [DisplayName("Some Date")]
    public DateTime SomeDate { get; set; }

    [Required]
    [DisplayName("Another Date")]
    public DateTime AnotherDate { get; set; }

    [DisplayName("A Third Date")]
    public DateTime? AThirdDate { get; set; }
}

View

@using (Ajax.BeginForm("AddItem", "Controller", new AjaxOptions
{
    UpdateTargetId = "add-item-section",
    LoadingElementId = "loading-image",
    HttpMethod = "POST",
}))
{
    <section id="add-item-section">
        <table>
            <tr>
                <th>@Html.LabelFor(m => m.NewItem.SomeDate)</th>
                <th>@Html.LabelFor(m => m.NewItem.AnotherDate)</th>
                <th>@Html.LabelFor(m => m.NewItem.AThirdDate)</th>
                <th></th>
            </tr>
            @Html.EditorFor(m => m.NewItem, "ViewModelEditorTemplate")
        </table>
    </section>
}

View Model Editor Template

@model ViewModel

<tr>
    <td>@Html.EditorFor(m => m.SomeDate)</td>
    <td>@Html.EditorFor(m => m.AnotherDate)</td>
    <td>@Html.EditorFor(m => m.AThirdDate)</td>
    <td><button type="submit" class="btn btn-info">Add</button></td>
</tr>

@Html.HiddenFor(m => m.ID)
@Html.HiddenFor(m => m.AnotherID)

Controller

[HttpPost]
public ActionResult AddItem(ViewModel item)
{
    // Breakpoint set here (code removed because it's irrelevant to this issue).
}


Download ajax.form.always.posting.viewmodel.with.null.values.mvc.4.zip
Direct Link


Download


Download ajax.form.always.posting.viewmodel.with.null.values.mvc.4.zip
Mediafire


Download


Download ajax.form.always.posting.viewmodel.with.null.values.mvc.4.zip
Badongo


Download


Download ajax.form.always.posting.viewmodel.with.null.values.mvc.4.zip
Extabit


Download


Download ajax.form.always.posting.viewmodel.with.null.values.mvc.4.zip
Zippyshare


Download