Gerald Hughes
Gerald Hughes

Reputation: 6159

Building Bootstrap template with @foreach from asp.net razor not as expected

I have a json with some objects. Using @foreach from Razor, I want to expose the results on a template, along with some filters that will filter my results.

The problem is that I can't render the template correctly. I want my sidebar/widget to be rendered one time one the right, and the results to be rendered one bellow another, and to look as you'd expect.

CODE:

@{int i = 0;}
@{
    var client = new WebClient();
    var json = client.DownloadString("http://example.com/raw/a5N8mJ2Y");
    var results = Json.Decode(json);
}

<div class="container">
    <div class="row">
        @foreach (var result in results)
        {
            i++;
            if (i == 2)
            {
                <!-- Left sidebar goes here -->
                <aside id="sidebar" class="col-sm-3">
                    <section id="filters">
                        <h3>Filtre</h3>
                        ...
                    </section>
                </aside>
            }
            <div style="border-style: groove; " class="col-sm-9">

                <!-- objects from json go here -->

            </div>
        }
    </div>
</div>

Screenshot:

enter image description here

Upvotes: 0

Views: 467

Answers (1)

Matthew Allen
Matthew Allen

Reputation: 821

If you want your sidebar to appear only once, it's pointless being in the foreach loop. It's getting put to the right and pushing the next item down because you're placing it between the results columns.

I think you should set it out so there is one aside element outside of the foreach loop and one column that contains the json items, e.g.

<div class="container">
    <div class="row">
        <!-- Left sidebar goes here -->
        <aside id="sidebar" class="col-sm-3">
            <section id="filters">
                <h3>Filtre</h3>
                    ...
            </section>
        </aside>
        <div class="col-sm-9">
        @foreach (var result in results)
        {
            <div class="item-result">
                <!-- object result here -->   
            </div>
        }
        </div>
    </div>
</div>

Then just style your .item-result class like:

.item-result{
    border-style: groove;
    display: block;
    margin-bottom: 15px;
}

Upvotes: 1

Related Questions