从表单中检索多行/记录

时间:2019-03-22 18:05:40

标签: c# asp.net-mvc

当我尝试从表单中检索数据时,我遇到了List为空的问题。它适用于Form Collection,但是当我尝试以列表形式返回时不起作用。

控制器

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Verify(List<VerifyVM> VC)
    {
        return 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>
}

型号

public class VerifyVM
{
    [Display(Name = "Course Name")]
    public string CourseName { get; set; }
    public string Cost { get; set; }
    public string ErrorMsg { get; set; }
}

1 个答案:

答案 0 :(得分:0)

当您尝试发布数据时,应将数据放在“输入”元素中。像这样

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

在您的Foreach内部,您应该创建“输入”元素。

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++;
}