0

I'm running into a problem where my List is null when I tried to retrieve data from my form. It works in Form Collection, but not when I try to return as a list.

Controller

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Verify(List<VerifyVM> VC)
    {
        return View();
    }

View

@model IEnumerable<Appliecation.Models.ViewModel.VerifyVM>
using (Html.BeginForm("Verify", "Sections", FormMethod.Post))
{
    @Html.AntiForgeryToken()
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>@Html.DisplayNameFor(model => model.CourseName)</th>
                        <th>@Html.DisplayNameFor(model => model.Cost)</th>

                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(model => item.CourseName, new { @class = "form-control" })@Html.HiddenFor(model => item.CourseName)
                            </td>
                            <td>
                                @Html.DisplayFor(model => item.Cost, new { @class = "form-control" })@Html.HiddenFor(model => item.Cost)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
            <div class="text-right">
                <button type="button" id="goback" class="btn">Back</button>
                <input type="submit" id="submit" value="Submit" class="btn" />
            </div>
}

Model

public class VerifyVM
{
    [Display(Name = "Course Name")]
    public string CourseName { get; set; }
    public string Cost { get; set; }
    public string ErrorMsg { get; set; }
}
Kane
  • 43
  • 6
  • `@Html.DisplayFor(model => item.CourseName` is likely rendering the wrong name in the html. Check out https://stackoverflow.com/questions/14822615/how-does-mvc-4-list-model-binding-work – Yuriy Faktorovich Mar 22 '19 at 18:12

1 Answers1

0

When you try to post data you should put data in "input" element. like this

<input type="text" value="some value" />

Inside your Foreach, you should create "input" elements.

int i = 0;  
foreach (var item in Model) 
{
    //Other stuff
    //because you want to get it in list you should send data as array, so the name
    //should contains index like this
    string elementName = "CourseName[" + i + "]";
    <input type"hidden" value="@item.CourseName" name="@elementName" />
    //Other stuff 
    i++;
}
Kiarash Alinasab
  • 794
  • 1
  • 4
  • 16