简体   繁体   中英

Separate code in views mvc

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!

您可以将JS代码放在一个外部文件中,并使用script标签在模板的head标签中调用它:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM