0

I have two dropdown lists in my view

For first dropdown list I have this code in View:

@Html.DropDownListFor(model => model.VacancyId, ViewBag.Teams as SelectList,new { @class = "greeting" })

And this in Controller

SelectList teams = new SelectList(db.Vacancy, "VacancyId", "VacancyName");
        ViewBag.Teams = teams;
        return View();

And here is model

 public partial class Vacancy
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Vacancy()
    {
        this.Interwiers = new HashSet<Interwier>();
        this.InvitationMails = new HashSet<InvitationMail>();
        this.Interviews = new HashSet<Interview>();
        this.MassLinks = new HashSet<MassLink>();
    }

    public int VacancyId { get; set; }
    [Display(Name = "Вакансия")]
    public string VacancyName { get; set; }
    public Nullable<int> CompanyID { get; set; }

    public virtual Company Company { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Interwier> Interwiers { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<InvitationMail> InvitationMails { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Interview> Interviews { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<MassLink> MassLinks { get; set; }
}

}

I need to set two dropdown lists . In one I select company, in second I will see vacancies related to this company. How to do this?

Thank's for help.

  • Do a search for "dependent dropdown" or "cascading dropdown" – jmoerdyk Mar 15 '17 at 23:01
  • Its called cascading dropdownlists - refer [this question/answer](http://stackoverflow.com/questions/28627421/better-way-to-load-2-dropdown-in-mvc/28640420#28640420) for an example. Also [this DotNetFiddle](https://dotnetfiddle.net/1bPZym) for a full implementation (and do not use data models in your view especially when editing - use [view models](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc)) –  Mar 15 '17 at 23:01
  • 3
    Possible duplicate of [connecting between two dropdownlist mvc 4](http://stackoverflow.com/questions/12249335/connecting-between-two-dropdownlist-mvc-4) – Muhammed Albarmavi Mar 15 '17 at 23:05

3 Answers3

1

You can use AJAX. I don't think that you can do it via Razor.

  • Agree with this statement. I had a similar issue and found it was a lot easier to deal with standard HTML select and options with javascript than the html helpers that come with razor. If you really want to use razor views you can try a partial view that only contains the dropdown helper that is retrieved from AJAX. – David Lee Mar 15 '17 at 23:28
  • 1
    Using razor has got nothing to do with this (razor is just for generating html) –  Mar 15 '17 at 23:55
0

I will give you an Example in MVC 5. Fetching VAT percentage for VAT Code,

Typescript/JS:

     function FetchVATDetails() {

    let ddlSender = "#ddlVATCode";
    let url = "/ExactSalesOrders/GetVATDetails";
    let ddlVatPercentage = "#ddlVATPercentage";
    let failureFunction = () => {
        $(ddlVatPercentage).html("");
        $(ddlVatPercentage).append(
            $('<option></option>').html("- No VAT Percentage -"));
    };

    let id = $(ddlSender).val();
    if (id != "" && id != null) {
        $.ajax({
            url: url,
            type: "GET",
            dataType: "JSON",
            data: { id: id },
            success(data) {
                if (data === false) {
                    failureFunction();
                } else {
                    $(ddlVatPercentage).html("");
                    $.each(data.VATPercentages,
                        (i, percentage) => {
                            $(ddlVatPercentage).append(
                                $('<option></option>').val(percentage.Percentage).html(percentage.Percentage));
                        });
                    $(ddlVatPercentage).change();
                }
            }
        });
    } else {
        failureFunction();
    }
}

Controller :

 public ActionResult GetVATDetails(string id)
        {
            var vat = ExactService.SelectObjectByCode<VATCode>(id);
            vat.VATPercentages = ExactService.SelectObjects<VatPercentage>().Where(x => x.VATCodeID == vat.ID).ToList();
            return vat != null ? Json(vat, JsonRequestBehavior.AllowGet) : Json(false, JsonRequestBehavior.AllowGet);
        }

Cheers

Lyubomir Dimov
  • 141
  • 1
  • 11
0

You can do it simply by using J-query Ajax.If you loaded first drop down values,add an OnChange method for that field, while on change put an Ajax call and pass your first drop down values and get the related values in db. Make sure you mapped the field values correctly in db.