1

I'd like to create a view that lists erorrs occured, while executing some action in a controller. I know how to create views while using a model, but can it be done without using a model? Just by passing simple list of strings?

I've created an action for the view with errors:

    public ActionResult ListOfErrors(List<string> listOfErrors)
    {
        return View(listOfErrors);
    }

And a view for this action:

@model List<string>

<table>
    <thead>
        <tr>
            <th>
                Error
            </th>
        </tr>
    </thead>

    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.ToString();
                </td>
            </tr>
        }
    </tbody>
</table>

If I do it like this I just get System.Collections.Generic.List``1[System.String];. What should I change?

Pomme
  • 87
  • 8
  • include the namespace int model declaration @model System.Collections.Generic.List – Vince Mar 25 '20 at 08:53
  • [Passing string as model](https://stackoverflow.com/a/22967178/7703386), should work with any type really. – Wubbler Mar 25 '20 at 09:35
  • @Wubbler I tried it but I'm not sure what to add in the view, I have `@model List` but if I run the code it still gives me only one record: System.Collections.Generic.List`1[System.String]; – Pomme Mar 25 '20 at 12:38
  • 1
    That is peculiar indeed, I made a sample [fiddle](https://dotnetfiddle.net/Xu1l8P) and everything works in there as expected. Calling `ToString()` on list of strings is unnecessary but I don't think that's the problem. – Wubbler Mar 25 '20 at 13:28
  • @Wubbler, ok, the problem was in passed argument to the ActionResult. My route values weren't correct in a "RedirectToAction" function. Now it works, thanks :) – Pomme Mar 25 '20 at 14:18
  • What are you submitting to the controller (i.e. what is in `List listOfErrors`)? – Kenneth K. Mar 25 '20 at 16:46
  • `foreach`ing a `list` means that `item` is a `string`, so there is no need to `ToString()` it... – Erik Philips Mar 25 '20 at 17:51

1 Answers1

0

You can set a variable into ViewBag with your desired name (mine is ErrorList) in your action:

public ActionResult Index()
{
    ViewBag.ErrorList = new List<string>() { "Error 1", "Error 2" };
    return View();
}

Then you can user this object in your view and do your magic:

<ul>
@foreach (string error in (List<string>)ViewBag.ErrorList)
{
    <li>error</li>
}</ul>
Renan Araújo
  • 3,533
  • 11
  • 39
  • 49
Alireza Mahmoudi
  • 964
  • 8
  • 35