@ Html.HiddenFor返回空值 [英] @Html.HiddenFor returning null value

查看:90
本文介绍了@ Html.HiddenFor返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将表的结果返回给控制器以进行进一步的操作.一旦返回到控制器,该值将显示为空.过去,我可以使用@ Html.HiddenFor返回值,但在这种情况下似乎无法正常工作.不知道我在这里做错了什么.任何帮助是极大的赞赏.

I am trying to return the results of a table back to the controller for further manipulation. Once returned to the controller the value shows as null. In the past I have been able to use @Html.HiddenFor to return the values but it doesn't seem to be working in this instance. Not sure what I am doing wrong here. Any help is greatly appreciated.

@model IEnumerable<Project.Models.Item>
@{
    ViewBag.Title = "Welcome to The Project";
 }


@using (Html.BeginForm("UpdateQuality", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    <div class="row">
        <div class="form-group">
            <table class="table table-bordered">
                <tr>
                    <th>@Html.DisplayNameFor(m => m.Name)</th>
                    <th>@Html.DisplayNameFor(m => m.SellIn)</th>
                    <th>@Html.DisplayNameFor(m => m.Quality)</th>
                </tr>
                @for (int i = 0; i < Model.Count(); i++)
                {
                    <tr>
                        <td>@Html.DisplayFor(m => m.ElementAt(i).Name)</td>
                        <td>@Html.DisplayFor(m => m.ElementAt(i).SellIn)</td>
                        <td>@Html.DisplayFor(m => m.ElementAt(i).Quality)</td>

                        @Html.HiddenFor(m => m.ElementAt(i).Name)
                        @Html.HiddenFor(m => m.ElementAt(i).SellIn)
                        @Html.HiddenFor(m => m.ElementAt(i).Quality)

                    </tr>
                }
            </table>
            <div class="form-group">
                <div style="margin-top: 50px">
                    <input type="submit" class="btn btn-primary" value="Advance Day"/>
                </div>
            </div>
        </div>
    </div>
}

这是返回null的控制器.

And here is the controller which returns null.

public ActionResult UpdateQuality(List<Item> Items )
{
    return View("Index", (object)Items);
}   

推荐答案

您不能在生成表单控件的HtmlHelper方法中使用ElementAt()(请查看生成的name属性-它与您的模型不匹配).

You cannot use ElementAt() in a HtmlHelper method that generates form controls (look at the name attribute your generating - it does not match your model).

将模型更改为IList<T>

@model List<Project.Models.Item>

并使用for循环

@for (int i = 0; i < Model.Count; i++)
{
    ....
    @Html.HiddenFor(m => m.[i].Name)
    ....

或更改对typeof Item使用自定义EditorTemplate,并在主视图中使用@Html.EditorFor(m => m)为集合中的每个项目生成正确的html.

or change use a custom EditorTemplate for typeof Item, and in the main view, use @Html.EditorFor(m => m) to generate the correct html for each item in the collection.

这篇关于@ Html.HiddenFor返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆