0

I know this question has been asked about 100 times, I've gone through them, i cant see anything that i might be doing wrong. Any help would be appreciated

When posting back the ImportModel list is empty.

@model Models.ImportModel
<div class="main-content">
<div class="container">
    <h1>Uploaded Cars</h1>
    @using (Html.BeginForm("Confirm", "Import", FormMethod.Post, new { @class = "form-horizontal" }))
    {
        <table id="importVehiclesTable" class="table">
            <thead>
                <tr>
                    <th>Registration</th>
                    <th>Details</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.Vehicles.Count; i++)
                {
                    <tr> 
                        <td>@Html.DisplayFor(m => m.Vehicles[i].RegistrationNumber)</td>
                        <td>@Html.DisplayFor(m => m.Vehicles[i].Name)</td>
                        <td></td>
                    </tr>
                }
            </tbody>
        </table>
        <br />
        <br />
    <input type="submit" value="Import Vehicles" class="btn btn-primary" />
    <input type="reset" value="Back" class="btn" onclick="history.back();" />
    }
</div>

My Model,

    /// <summary>
/// 
/// </summary>
public class ImportModel : BaseModel
{
    /// <summary>
    /// Gets or sets the cars.
    /// </summary>
    /// <value>
    /// The cars.
    /// </value>
    public List<VehicleAddViewModel> Vehicles { get; set; }
}

my action, but the Vehicles obj is null.

        [HttpPost]
    public ActionResult Confirm(ImportModel importModel)
    {
        //Will be saving to the DB here

        return null;
    }
InitLipton
  • 2,395
  • 5
  • 30
  • 47
  • Can you show your `Get` action? – ediblecode Feb 26 '15 at 14:55
  • 1
    You are using DisplayFor() MVC won't post Back this. try putting them in HiddenFor or TextBoxFor() Related: http://stackoverflow.com/questions/12314849/html-displayfor-not-posting-values-to-controller-in-asp-net-mvc-3 – Dawood Awan Feb 26 '15 at 14:58
  • Also see answer here: http://stackoverflow.com/questions/18448247/displayfor-is-not-keeping-data-in-viewmodel-on-postback – Dawood Awan Feb 26 '15 at 14:59
  • @DawoodAwan cheers, that makes sense. It worked when i used TextBoxFor(). post as answer and i'll accept. thanks – InitLipton Feb 26 '15 at 15:07

1 Answers1

2

You are using DisplayFor() MVC won't post Back this.

try putting them as a form element

HiddenFor() or TextBoxFor()

Related Answers:

DisplayFor is not keeping data in ViewModel on PostBack

Html.DisplayFor not posting values to controller in ASP.NET MVC 3

Community
  • 1
  • 1
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119