【问题标题】:How to get a list/array from a view back to the controller如何从视图中获取列表/数组返回到控制器
【发布时间】:2011-12-07 01:02:25
【问题描述】:

我的 ViewResult 控制器:

    public ViewResult Controller(int id)
    {
        List<Data> dataList = dataAccess.getDataById(id);
        Results[] resultArray = new Results[dataList.Count];
        ViewBag.results= resultArray;
        return View(dataList);
    }

我的观点:

@model IEnumerable<Solution.Models.Data>

@{
    Solution.Models.Results[] res= ViewBag.results;
}


@using (Html.BeginForm()) {
<table>
@{

    int i = 0;
    foreach (var item in Model) {
    <tr>
        <td>
            Snippet: @Html.DisplayFor(modelItem => item.text)
        </td>

    </tr>
    <tr>
        <td>
            Translation: @Html.EditorFor(modelItem => res[i].text)
        </td>
    </tr>
    i++;
    }
}
</table>
<p>
    <input class="CRUD-buttons" type="submit" value="Send" />
</p>
}

我的控制器 ActionResult:

    [HttpPost]
    public ActionResult Controller(/*List<Data> dataList, */Results[] results)
    {
        ResultText = results[0].text; //NullReferenceException
    }

dataList 和结果为空。我在 stackoverflow 上阅读了几篇文章,但找不到解决方案。

我已经查看了以下博客 (link),但它的 MVC 2 代码。 :(

【问题讨论】:

  • 请不要在标题前加上“C# MVC 3:”。这就是标签的用途。

标签: c# asp.net-mvc-3 list view controller


【解决方案1】:

有多种方法可以做到这一点。什么让你在这里是为了让你收到results参数,生成的编辑控件的name应该是results[0],第二个是results[1],等等,索引中没有间隙(这是因为表单发布时how DefaultModelBinder expects to find the fields named)。

因此,一种直接(虽然不是很好)的解决方案是正确指定名称:

@Html.TextBox(string.Format("results[{0}]", i), res[i].text)

更好的解决方案是将results 放入您的模型中(更好的是,在专门为此视图创建的 ViewModel 中)。例如,首先创建一个类,封装一条数据和对应的结果:

class ItemViewModel
{
    Solution.Models.Data TheData { get; set; }
    Solution.Models.Results TheResults { get; set; }
}

然后您可以让您的视图将这些项目的集合作为其模型:

@model IEnumerable<ItemViewModel>

然后用

输出编辑控件
Translation: @Html.EditorFor(modelItem => modelItem.TheResults)

最后,您修改回发操作以接受ItemViewModel 的数组:

[HttpPost] 
public ActionResult Controller(ItemViewModel[] results) 

一般建议:尽量避免将EditorFor 用于不属于视图模型的对象(例如,通过ViewBagViewData 传递的对象)。如果你这样做,MVC 会惩罚你。

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多