0

I have a view Index, which is the first page of my website. I have 3 cascade dropdowns on the page, the dropdowns are filled based on the previous dropdown. I used jquery and json to resolve that, it works fine, all the code is on the Index.cshtml.

Now, I need to show these dropdowns in almost all pages of the website. I have created a partial view, where I copied the dropdowns, as you can see here:

<div class="col-sm-4">
    <div style="padding-top:15px;">
        <form class="form-control-static">
            <div class="form-group">
                <div class="row">
                    <div class="col-sm-10">
                        @if (ViewData.ContainsKey("makes"))
                        {
                            @Html.DropDownList("makes", ViewData["makes"] as List<SelectListItem>, "--Select car--", new { @class = "dropdown-toggle form-control" })
                        }
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-10">
                        <p></p>
                        @Html.DropDownList("models", new SelectList(string.Empty, "Value", "Text"), "--Select model--", new { @class = "dropdown-toggle form-control" })
                    </div>
                </div>
                <div class="row">
                    <p></p>
                    <div class="col-sm-10">
                        @Html.DropDownList("engines", new SelectList(string.Empty, "Value", "Text"), "--Select engine--", new { @class = "dropdown-toggle form-control" })
                    </div>
                </div>
            </div>

        </form>

    </div>
</div>

<div class="col-sm-4" style="height: 10em;display: flex;align-items: center ; padding-top:25px;">
    <input type="submit" id="btnSearch" class="btn btn-default active" value="Search" disabled="disabled" style="width:150px;" />
</div>

but the logic for filling the dropdowns are still in the Index.cshtml. Althought I tried to copy the javascript code in the newly created partial view, the dropdowns are not filling with data properly. It works fine only when I am on the first page. Can you please give me some hints what would be the best way to resolve something like this. Thank you!

Orsi
  • 545
  • 2
  • 10
  • 27
  • Are the other pages in the same Controller? – jao Feb 16 '17 at 07:34
  • I have in other controllers too – Orsi Feb 16 '17 at 07:35
  • Maybe you could use a ChildAction: http://stackoverflow.com/questions/12530016/what-is-an-mvc-child-action and https://blog.falafel.com/child-actions-asp-net-mvc/. Just move your ViewData logic to the childaction and call the childaction in your main view. – jao Feb 16 '17 at 07:40

1 Answers1

1

You can put the JS code in an external file and call it in the head tag in the template using script tag:

Iaconis Simone
  • 282
  • 3
  • 12