1

我一直无法弄清楚如何在网页上编辑表格项目,并将它们发布回服务器。(实际上,在这种情况下,我只是希望用户选择复选框,就好像他们正在选择多个项目,但这只是暗示)。

问题是,当视图显示在网页上时,在 HttpPost 中,picSelections 为空。

这是我的视图的顶部:

@model IEnumerable<CarShow.lmit_pics>

@using (Html.BeginForm())
{    
<div style="width:100%; height:60px; ">
<input type="submit" value="Add Selected Photo(s) to Survey" />
</div>

    for (int i = 0; i < Model.Count(); i++)
    {
        var item = Model.ElementAt(i);
    <div style="width:296px; float:left">

            <div style="float:left; width:200px; margin-bottom:18px">

                @{string cropped = "../../../Content/Images/" + Html.DisplayFor(modelItem => item.picname).ToString() + "?" + Html.DisplayFor(modelItem => item.version).ToString();
                 }
                <img alt="picture" class="pic-size" src="@cropped" />
                <br />
                    @Html.EditorFor(modelItem => item.brand)
            </div>

</div>
        }    
}
</div>

这是在控制器中:

public ActionResult AddSurveyPic(string id)
{
   var validPicSummaries = (IEnumerable)(from x in db.lmit_pics where x.enabled == 1 select x);
   return View((IEnumerable)validPicSummaries);
}

[HttpPost]
public ActionResult AddSurveyPic(IEnumerable<CarShow_MVC.lmit_pics> picSelections)
{
        // Save data here
}

谢谢。

4

1 回答 1

3

不要在视图中编写循环。我建议您使用编辑器模板:

@model IEnumerable<CarShow.lmit_pics>

@using (Html.BeginForm())
{    
    <div style="width:100%; height:60px; ">
        <input type="submit" value="Add Selected Photo(s) to Survey" />
    </div>
    @Html.EditorForModel()
}

然后创建一个相应的编辑器模板,该模板将自动为模型的每个元素呈现:~/Views/Shared/EditorTemplates/lmit_pics.cshtml. 注意模板的名称和位置很重要:

@model CarShow.lmit_pics

<div style="width:296px; float:left">
    <div style="float:left; width:200px; margin-bottom:18px">
        @{string cropped = "../../../Content/Images/" + Html.DisplayFor(x => x.picname).ToString() + "?" + Html.DisplayFor(x => x.version).ToString(); }
        <img alt="picture" class="pic-size" src="@cropped" />
        <br />
        @Html.EditorFor(x => x.brand)
    </div>
</div>

You might also want to read the following article to better understand the naming conventions that the default model binder uses when binding collections and dictionaries.

于 2012-05-31T05:58:17.363 回答