0

So I'm curious to how I would render paragraphs inside a div based on the content I have in a List...

So picture this.

List<string> names = new List<string>
names.add("Foo");
names.add("Bar");

How would I make that generate something along the lines of

<div>
<p>Foo</p>
<p>Bar</p>
</div>
Riley Varga
  • 670
  • 1
  • 5
  • 15

1 Answers1

2

Add the names List into your Model Or as you model in the controller (in the code below i pass it as the model).

     public ActionResult Home()
    {
        List<string> model = new List<string>();
        model .Add("Foo");
        model .Add("Bar");

        return View(model );
    }

Then just add this into your view:

@model IList<String>


<div>
@for (int i = 1; i < Model.Count; i++)
{
    <p>@Model[i]</p>
}</div>
Feronimus
  • 123
  • 10
  • Will this update realtime or will I need to refresh the browser everyime something is added to the List? – Riley Varga Jan 03 '20 at 11:19
  • This will not update your model. Where and how are you going to update your list? – Feronimus Jan 03 '20 at 11:23
  • 1
    controllers run on server side, so list will not be updated when you add something in that at run time. For this, you have to refresh your page @RileyVarga. Explain your scenario in a bit more detail, only then we will be able to help you – Waleed Naveed Jan 03 '20 at 11:43
  • No I want to update the View from the Controller, so in my Controller I would have my List lets say I have a function that runs every 10 seconds and on the callback it adds a new string to the list, would it then update the view do you think? – Riley Varga Jan 03 '20 at 11:44
  • no, to update the view with model, you have to call the controller again @RileyVarga – Waleed Naveed Jan 03 '20 at 11:46
  • Wouldnt that refresh the page? – Riley Varga Jan 03 '20 at 11:47
  • have to used AJAX ? @RileyVarga. It might solve your problem – Waleed Naveed Jan 03 '20 at 11:47
  • A controller returns a renderd view when it gets called. It creates and servers a single html-css-js page. So if you want to update your view you have to create a new one. What you want is to use AJAX(Javascript library) and update part of your view. You can find similiar event like examples on uses of AJAX with lazy loading. – Feronimus Jan 03 '20 at 11:54