skip to Main Content

I have a page where I have an empty dropdown list, I need to use radio buttons in order to generate the elements inside. everything is working perfectly, I am getting the data when I debug the code, the one problem I have which is a really simple problem is that I can’t append the data into the dropdown list for some reason, I have tried almost all the answers I found on here, but non of them worked.

this is my procedure class, i call this from my controller

public class Procedures
    {

        public List<SelectListItem> SelectAnswer(int questionid)
        {
            List<SelectListItem> ds = new List<SelectListItem>();
            //      var connection = ConfigurationManager.
            //ConnectionStrings["MyConnection"].ConnectionString;
            String Con = CONNECTION STRING ONLY;
            try
            {
                using (SqlConnection con = new SqlConnection(Con))
                {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand("SelectAnswer", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@questionid", SqlDbType.Int).Value = questionid;

                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        var dataReader = cmd.ExecuteReader();
                        while (dataReader.Read())
                        {
                            var item = new SelectListItem();
                            item.Text = dataReader["QuestionDesc_F"].ToString(); 
                            
                            ds.Add(item);
                        }
                    }
                    con.Close();
                }
            }
            catch (Exception ex)
            {

            }
            return ds;


        }

    }
}

my controller

 public ActionResult SelectAnswer(int questionid)
        {
            Question_OptionIndexModel provinces = new Question_OptionIndexModel();
            
            var ds = new Procedures().SelectAnswer(questionid);
            
          

            
            return Json(ds.ToList());



        }

view

This is where it all goes wrong, data is being sent and I can listen to it with my console; so I know the data is being transferred correctly, problem is with the append, the jquery function is kind of weird but it was my last try before I knew I needed help

ps. I know I am only sending text from my procedure class, but I was putting it to the side until the text worked, I was using static variable that increments by one as the value

$("input[name='radio']").on("change", function addQuestion() {
  $('#answerSelectList').dataTable().fnClearTable();
  var questionid = this.value;
  var eleUpdate = $('#offerDropdown');
  $.ajax({
    type: "post",
    url: '@Url.Action("SelectAnswer", "Question_Option")',
    ajaxasync: true,
    data: {
      questionid: questionid
    },
    success: function(data) {
      $(eleUpdate).find('option').remove();
      $(eleUpdate).append('<option value="">@GetResource("Label.Global.Select")</option>');
      $.each(data, function(index) {
        var $option = $('<option>');
        $option
          .val(index)
          .text(data[index].text);
        $(eleUpdate).append($option);
      });
      $(eleUpdate).val('').trigger('change');
    },
    error: function(data) {}
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div class="form-control">
  <div id="radio">
    <input type="radio" id="radio1" name="radio" value="1" /><label for="radio1">Choice 1</label>
    <input type="radio" id="radio2" name="radio" value="2" /><label for="radio2">Choice 2</label>
    <input type="radio" id="radio3" name="radio" value="3" /><label for="radio3">Choice 3</label>
  </div>
</div>
<select id="offerDropdown" class="form-control">
</select> //I need to append here

2

Answers


  1. Chosen as BEST ANSWER
    was inside a wrong div, just moved it to a different place.

  2. This is the controller

      [HttpPost]
            public ActionResult GetCustomerByBranch(string example)
            {
                MyContext db = new MyContext();
    
                var _Customer = Common.getDataCollection(example);
    
                var result = _Customer.OrderBy(a => a.Code).Select(a => new SelectListItem { Value = a.Pkey.ToString(), Text = a.Code + " " + a.Name })
                  .ToList();
    
                return Json(result);
    
                
            }
    

    This is part of my view. When the customer change the value of the example dropdownlist, the customer dropdownlist will be referesh.

    <div class="form-group">
                @Html.LabelFor(m => m.ExampleId, new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.EnumDropDownListFor(m => m.ExampleId, new { @class = "form-control" })
                </div>
            </div>
    
    <div class="form-group">
            @Html.LabelFor(m => m.CustomerId, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.CustomerList, Model.CustomerList, "-Select-", new { @class = "form-control" })
            </div>
        </div>
    
    
    @section Scripts {
    
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/jqueryAjax")
    
    
     <script>
    
            $("#ExampleId").change(function () {
    
                $.ajax({
                    url: "/Customer/GetCustomerByBranch",
                    type: "post",
                    data: {
                        example: $("#ExampleId").val()
                    }
                }).done(function (response) {
                    $("#CustomerId").empty();
                    $.each(response, function (i, item) {
                        $("#CustomerId").append($("<option>").text(item.Text).val(item.Value));
                    });
                });
    
            });
    
    
        </script>}
    

    You may add alert in the javascript to check which section that the script can reach and remember you may have to clear cache after you modify and re-run the project.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search