错误列表<> Html助手中的值

时间:2015-05-05 21:05:12

标签: asp.net-mvc

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

在此示例代码中,如果我将值30更改为0并提交,则视图应显示4个输入值为“10,20,40,50”,但如果我,则为“10,20,0,40”使用任何HtmlHelper,如EditorFor ou TextBoxFor。

如果我用输入标签替换html助手,一切正常。

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" />
}

1 个答案:

答案 0 :(得分:1)

嗯,这是一个棘手的问题。老实说,我无法找出正在发生的事情。我认为这可能是一个浏览器问题,但是在检查网络选项卡时,您会注意到表单实际上返回了错误的数据。

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

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

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

    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参数),只需找到适当的覆盖。

正如我所说,我没有回答你的原始问题,而是针对另一个问题提出解决方案。