Three33Steele
Three33Steele

Reputation: 51

Select values from Json to add to dropdown list

I am needing to select values from a JSON, that is created based off a SQL Server database, and add them to a dropdown list as value seleciotns. I am using asp.net MVC. Everything seems to be working, excpet I can not figure out how to select "value" and "name" from my Json and use them. All I need help with is selecting those varibles and using them in the code.

This is my javascript function

    $(function () {
        $("#ddlDepartments").change(function () {
            var selectedid = $('option:selected').val();
            var ddlSubDepartments = $("#ddlSubDepartments"); //get the dropdownlist

            if (selectedid > 0) {
                $.ajax({
                    url: "/RecordEntries/PopulateddlSubDepartments",
                    data: {
                        id: selectedid
                    },
                    type: "Post",
                    dataType: "Json",
                    success: function (data) {
                        alert(data);
                        ddlSubDepartments.html("");
                        ddlSubDepartments.append($('<option></option>').val("").html("Please select a Sub Department"));
                        for (var i = 0; i < data.length; i++) {

                            ddlSubDepartments.append($('<option></option>').val(value[i]).html(name[i]));
                        }
                    },
                    error: function () {
                        alert('Failed to retrieve Sub Departments.');
                    }
                });
            }
        });
    });

And my JSON is like this, it can be edited to whatever format.

{"value":5,"name":"Sub Department 1"},{"value":8,"name":"Sub Department 2"}

EDIT: I'll add in my controller action that the jscript is calling at the beginning.

        public ActionResult PopulateddlSubDepartments(int id)
        {
            var query = from d in _context.SubDepartments
                        where d.DepartmentId == id
                        select "{\"value\":" + d.SubDepartmentId + "," + "\"name\":\"" + d.SubDepartmentName + "\"}";

            if (query == null)
                ViewBag.SubDepartments = false;
            else
                ViewBag.SubDepartments = true;

            return Json(query.ToList());
        }

Upvotes: 1

Views: 3639

Answers (4)

Serge
Serge

Reputation: 43890

try to fix action

 public ActionResult PopulateddlSubDepartments(int id)
        {
            var query = _context.SubDepartments
                        .Where(d=> d.DepartmentId == id)
                        .Select ( i=> new {
                           Value= i.SubDepartmentId,
                           Name= i.SubDepartmentName
                           }).ToList();

            if (query == null)
                ViewBag.SubDepartments = false;
            else
                ViewBag.SubDepartments = true;

            return Json(query);
        }

and ajax can be simplified too

 ddlSubDepartments.html("");
.....

success: function (result) {
                    
        var s = '<option value="-1">Please Select </option>';
        for (var i = 0; i < result.length; i++) 
       {
        s += '<option value="' + result[i].value + '">' + result[i].name + '</option>';
        }

        $('#ddlSubDepartments').html(s);
},

Upvotes: 2

persian-theme
persian-theme

Reputation: 6638

Perform the following steps

  1. add class JsonData
public class JsonData
{
    public string HtmlMsg { get; set; }
    public string HtmlBody { get; set; }
    public bool Success { get; set; }
}

2.add ViewHelper class

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

public static class ViewHelper
{
    public static string RenderPartialToString(this ControllerBase controller, string partialViewName, object model)
    {
        IView view = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
        return RenderViewToString(controller, view, model);
    }
    public static string RenderViewToString(this ControllerBase controller, IView view, object model)
    {
        using (var writer = new StringWriter())
        {
           controller.ViewData.Model = model;
           var viewContext = new ViewContext(controller.ControllerContext, view, controller.ViewData, controller.TempData, writer);
           view.Render(viewContext, writer);
           return writer.GetStringBuilder().ToString();
        }
    }
}

3.change PopulateddlSubDepartments to :

public ActionResult PopulateddlSubDepartments(int id)
{
  List<SubDepartment> model = (from d in _context.SubDepartments
         where d.DepartmentId == id
         select d).ToList();

   if (query == null)
      ViewBag.SubDepartments = false;
    else
      ViewBag.SubDepartments = true;

   return Json(new JsonData()
   {
        HtmlMsg = "",
        HtmlBody = this.RenderPartialToString("_DropDownList", model),
        Success = true,
   });
}

4.in your view change to

//...........................
<div class="row" id="tmpDropDownList">
      @Html.Partial("_DropDownList", Model)
 </div>
//...........................

5.add partialview _DropDownList

 @model List<namescpace.SubDepartment>
 @Html.DropDownList("ddlDepartments", new SelectList(Model, "SubDepartmentId", "SubDepartmentName"), "--please select--")
  1. add script
$(function() {
  $("#ddlDepartments").change(function() {
    var selectedid = $('option:selected').val();

    if (selectedid > 0) {
      $.ajax({
        url: "/RecordEntries/PopulateddlSubDepartments",
        data: {
          id: selectedid
        },
        type: "Post",
        dataType: "Json",
        success: function(result) {
          $("#tmpDropDownList").html(result.HtmlBody);
        },
        error: function() {
          alert('Failed to retrieve Sub Departments.');
        }
      });
    }
  });
});

Upvotes: 0

Mohamed BEN KHOUYA
Mohamed BEN KHOUYA

Reputation: 112

you need to deserialize it to plain objet like this:

let obj = JSON.parse(data); // now it looks like this : {value: 5, ...}
ddlSubDepartments.append($('<option
</option>').val(obj['value']).html(obj['name']));

Upvotes: 0

GH DevOps
GH DevOps

Reputation: 420

value[i] doesn't exist. Try:

ddlSubDepartments.append($('<option></option>').val(data.value[i]).html(data.name[i]));

Upvotes: 0

Related Questions