Reputation: 219
I have two dropdownlists in my View
First display Companies , second Vacancies related to that specific company.
So when I select company, I see in second selector Vacancies related to it
Here is code in View
<div class="right-grid-in-grid" style="width:100%;">
<div style="margin-left:20px;width:50%; ">
@Html.DropDownList("Company", ViewBag.Companies as SelectList, "Компания", new { @class = "greeting" })
@Html.ValidationMessageFor(model => model.VacancyId, "", new { @class = "text-danger" })
</div>
<div style="margin-left:20px;width:100%">
<select name="id" id="vacancy" style="width:55%" class="greeting" data-url="@Url.Action("Vacancies","Questions")" >
<option value="" disabled selected>Вакансия</option>
</select>
</div>
</div>
and I fill second selector with AJAX call like this
<script>
$(function () {
$("#Company").change(function (e) {
var $vacancy = $("#vacancy");
var url = $vacancy.data("url") + '?companyId=' + $(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
</script>
My problem in this: when I select company first time I see all vacancies related to it. But when I select another company, I will see vacancies from first company and vacancies from second company.
How I can fix this?
Upvotes: 0
Views: 26
Reputation: 1022
You've missed clearing your vacancies dropdown at change event of company. so add $("#vacancy").empty();
in your Script code.
<script>
$(function () {
$("#Company").change(function (e) {
$("#vacancy").empty();
var $vacancy = $("#vacancy");
var url = $vacancy.data("url") + '?companyId=' + $(this).val();
$.getJSON(url, function (items) {
$.each(items, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
});
});
});
Upvotes: 2