首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Helpers中错误的List<>值

Helpers中错误的List<>值
EN

Stack Overflow用户
提问于 2015-05-06 05:05:12
回答 1查看 32关注 0票数 0

我有一个包含可以编辑的整数列表的ViewModel。在post事件中,等于0的元素被删除,列表被重新排序。

在这个示例代码中,如果我将值30更改为0并提交,视图应该显示4个值为"10,20,40,50“的输入,但是如果我使用EditorFor ou TextBoxFor这样的HtmlHelper,我会得到"10,20,0,40”。

如果我用一个input标记替换html helper,一切都可以正常工作。

代码语言:javascript
复制
public ActionResult IntegerList()
{
    return View(new IntegerListViewModel() { List = new List<int>() { 10, 20, 30, 40, 50 } });
}

[HttpPost]
public ActionResult IntegerList(IntegerListViewModel integerListViewModel)
{
    integerListViewModel.List = integerListViewModel.List.Where(i => i > 0).OrderBy(i => i).ToList();
    return View(integerListViewModel);
}

public class IntegerListViewModel
{
    public IList<int> List { get; set; }
}

// @ view
@using (Html.BeginForm())
{
    for (int i = 0; i < Model.List.Count; i++)
    {
        <div>
            @Html.EditorFor(integer => Model.List[i]) // Wrong output
            @Html.TextBoxForFor(integer => Model.List[i]) // Wrong output
            <input type="text" value="@Model.List[i]" /> // Correct output
            @Model.List[i].ToString() // Correct output
        </div>
    }
    <input type="submit" />
}
EN

回答 1

Stack Overflow用户

发布于 2015-05-06 09:49:12

好吧,这是一个棘手的问题。老实说,我不知道发生了什么事。我以为这可能是浏览器的问题,但是查看网络选项卡,您会注意到表单实际上返回了错误的数据。

我在这里发布的不是一个解决方案,而是一个也能解决这个问题的建议:PRG

当您具有返回视图的POST操作时,您可以接受重复的事务。因为浏览器发送的最后一个请求是那个POST,所以如果用户点击F5,它将再次发送POST。

您可以使用以下示例轻松解决此问题:

代码语言:javascript
复制
    public ActionResult IntegerList()
    {
        var model = new IntegerListViewModel() { List = new List<int>() { 10, 20, 30, 40, 50 } };

        if (this.TempData.ContainsKey("IntegerList"))
            model.List = (List<int>)this.TempData["IntegerList"];

        return View(model);
    }

    [HttpPost]
    public ActionResult IntegerList(IntegerListViewModel integerListViewModel)
    {
        var list = integerListViewModel.List.Where(i => i > 0).OrderBy(i => i).ToList();

        this.TempData.Add("IntegerList", list);

        return this.RedirectToAction("IntegerList");
    }

我使用TempData将数据从一个操作发送到另一个操作,这很好。您也可以使用此重定向发送URL参数(GET参数),只需找到适当的覆盖即可。

正如我所说的,我不是在回答你最初的问题,而是用另一个问题的建议来解决它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30063237

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档