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

2 Answers 2

1

Why not just use TempData.Add(Alerts.ERROR, errors.Select(c => c.ErrorMessage).ToArray()) and iterate over the errors in your view?

2
  • Hi - thank you - I tried that, but it just says System.String[] in the view (I've added a screenshot to the post).
    – Mark
    Commented Jun 3, 2013 at 19:47
  • Yes -- you need to iterate over the errors, something like: if (TempData[Alerts.ERROR] != null && TempData[Alerts.ERROR].Length > 0) { foreach(string message in TempData[Alerts.ERROR]) { <div>@message</div> }}
    – wgraham
    Commented Jun 3, 2013 at 19:48
1

TempData is a dictionary, so it makes sense that trying to add a duplicate key causes an exception. Depending on how you show the contents of TempData, you either want to concatenate the error messages into one string, or use a key that has a Guid appended to it (thereby making the key unique every time).

One possible workaround (within your loop):

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);
}

This naively assumes you've previously formatted your error messages, and will produce one long string. If you're using, say, a <ul> to display the errors, you would wrap each error message in a <li></li>, then concat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.