1

I'm using the twitter bootstrap nuget package for MVC.

When posting to my controller, and checking for errors however, if I have more than one error in my model, I get the following error when trying to add a second alert to TempData:

An item with the same key has already been added.

    //
    // POST: /Customer/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Customer customer)
    {
        var errors = ModelState.Values.SelectMany(v => v.Errors);
        if (ModelState.IsValid)
        {
            // save to database etc
            // redirect to action
        }
        foreach (var c in errors)
        {
            TempData.Add(Alerts.ERROR, c.ErrorMessage);  // Error is reported here
        }

The error messages are difference, as shown below - so it must be that Alerts.ERROR is only allowed once: ss

Is there any way of adding two Alerts.Error error messages to TempData - or should I just concatenate a string, and add one error with combined error messages?

If I change the TempData code to:

TempData.Add(Alerts.ERROR, errors.Select(c => c.ErrorMessage).ToArray());

...the view renders as:

ss2

Thank you,

Mark

4

2 回答 2

1

TempData是字典,因此尝试添加重复键会导致异常是有道理的。根据您显示 内容的方式TempData,您要么希望将错误消息连接成一个字符串,要么使用Guid附加了 的键(从而使键每次都唯一)。

一种可能的解决方法(在您的循环内):

if (TempData.ContainsKey(Alerts.ERROR))
{
    string temp = TempData[Alerts.ERROR].ToString();
    TempData[Alerts.ERROR] = string.Concat(temp, c.ErrorMessage);
}
else
{
    TempData.Add(Alerts.ERROR, c.ErrorMessage);
}

这天真地假设您之前已经格式化了错误消息,并且会产生一个长字符串。例如,如果您使用 a<ul>来显示错误,则可以将每个错误消息包装在 a 中<li></li>,然后进行 concat。

于 2013-06-03T20:18:41.193 回答
1

为什么不直接使用TempData.Add(Alerts.ERROR, errors.Select(c => c.ErrorMessage).ToArray())和迭代视图中的错误?

于 2013-06-03T19:40:04.920 回答