-2

I have 2 dropdown called medication and strength.while selecting a medication the strength dropdown should populate based on the input of medication dropdown. HTML CODE:

<label>Medication<sup>*</sup></label> @Html.DropDownListFor( Model => Model.medication, Model.medication, htmlAttributes: new { id = "MyId" , style = "width:200px; height :30px"})   <button type="button" style="height:30px;" onclick="return openmedication()">search</button>                                
<label>Strength</label>@Html.DropDownListFor(Model => Model.strength, Model.strength, "Select Strength", new { style = "width:200px; height :30px" })  

**when i run this code i am getting all the values of strength dropdown from the table.without sorting the values depending on medication.

MY MODEL:**

 public List<ItemModel> med()//FOR MEDICATION
    {

        List<ItemModel> itemList = new List<ItemModel>();
        connection();
        SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@PstrOperationFlag", "S-drugname");
        con.Open();
        SqlDataAdapter sd = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sd.Fill(dt);
        ItemModel item = new ItemModel();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            ItemModel io = new ItemModel();
            while (sdr.Read())
            {
                io = new ItemModel();
                io.medicat = sdr["drugname"].ToString();


                itemList.Add(io);

            }
        }
        con.Close();
        return itemList;
    }
  public List<SelectListItem> Add()// FOR STRENGTH
    {

        List<SelectListItem> items = new List<SelectListItem>();
        connection();

        SqlCommand cmd = new SqlCommand("procmedication_dropdown1", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@pstroperationflag", "S-strength");

        con.Open();
        using (SqlDataReader sdr = cmd.ExecuteReader())
        {
            while (sdr.Read())
            {
                items.Add(new SelectListItem
                {
                    Text = sdr["strength"].ToString(),
                    Value = sdr["strength"].ToString()
                });
            }
        }
        con.Close();
        return items;
    }
Mark Antony
  • 39
  • 13
  • Kindly check the below link:- [Cascading dropdown in mvc](https://stackoverflow.com/questions/5497524/easiest-way-to-create-a-cascade-dropdown-in-asp-net-mvc-3-with-c-sharp) – Tejinder Singh Jul 27 '17 at 09:51
  • You need ajax. Refer [this answer](http://stackoverflow.com/questions/28627421/better-way-to-load-2-dropdown-in-mvc/28640420#28640420) for an example –  Jul 27 '17 at 09:51

2 Answers2

0

You can achieve this using jquery like this.

 $(document).ready(function(){
    $("#medication").on("change",function(){
       getStrengthList();
    });
 });

function getStrengthList() {
    var url = "Add" // Url of controller

    $.ajax({
        url: url,
        timeout: 500000,
        type: "GET",
        beforeSend: ShowLoader,
        success: function (data) {
            HideLoader();
            var selectList = $('#strength');
            selectList.find('option').remove().end();

            if (data.length > 0) {
                var selected = "";
                var selectedName = "";
                var i = 0;
                $.each(data, function (key, data) {
                    selectList.append('<option value="' + data.Value + '">' + data.Text + '</option>');

                    if (i == 0) {
                        selected = data.Value;
                        selectedName = data.Text;
                        i++;
                    }
                });
                selectedCategory = selected;
                selectedCategoryName = selectedName.toLowerCase();
                selectList.val(selected);
            }

        },
        complete: function () {

        },
        error:  function () {

        },
    });
}
jignesh patel
  • 964
  • 7
  • 13
  • i need not do anything in sql server bro? im getting the values of both dropdown from database. – Mark Antony Jul 27 '17 at 09:59
  • @ashwanth my code not doing anything in sql. Just calling one ajax request to your Add() method to get list of `strength` by `medication` and binding it to `medication` dropdownlist. – jignesh patel Jul 27 '17 at 10:09
  • @ashwanth also change url with your and also pass selected `medicationid` to get list by `medication ` – jignesh patel Jul 27 '17 at 10:11
0

Try the below Code

View:

//Load Medication Data on Page Load
    @Html.DropDownListFor( Model => Model.medication, Model.medication, htmlAttributes: new { id = "MyId" , style = "width:200px; height :30px"}) 

//Load Strength data on change of medication from ajax call                             
    @Html.DropDownListFor(Model => Model.strength, Model.strength, "Select Strength", new { style = "width:200px; height :30px" })  

Scripts:

   $("#MyId").on('change', function() {
   //Get the value of Medication dropdown
     var medicationId = $("#MyId").val();
    $.ajax({
            url: '@Url.Action("GetStrengthDropdown","Controller")',
            type: 'GET',
            dataType: 'json',
             data:medicationId :medicationId ,
             success: function(data) {

            $.each(data, function (i) {
                var optionhtml = '<option value="' +
                data[i].Value + '">' +data[i].Text + '</option>';
                $("#strength").append(optionhtml);
            });

            }
        });
    });

Controller:

public JsonResult GetStrengthDropdown(int medicationId)
{
 // DB call to get dropdown Values.
return JSON(values);
}
MOHAN V
  • 46
  • 1
  • 8