1

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());
        }

4 Answers 4

2

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);
},
Sign up to request clarification or add additional context in comments.

8 Comments

"The name d does not exist in the current context."
@Three33Steele Sorry, it is a typo, use i.SubDepartmentId and i.SubDepartmentName
Now my alert returns [object Object],[object Object],[object Object]. Is that what it should be? It still is not populating the ddl. The answer from @mohamed BEN KHOUYA works well but is only working for records where there is only one value.
You have to use alert(JSON.stringify(result)); And I updated my answer, pls check again.
Works like an absolute charm!! Thank you so much! This wasn't in my question because I wasn't at that point now, but I need to make one that reads two dropdowns values and selects options based off those. Should I post a whole other question for that?
|
0

value[i] doesn't exist. Try:

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

3 Comments

That didn't work. My dropdown did not have a value or text with that. This has been my problem. Is my Json formatted correctly? Do I need to use a parse? Maybe even a split?
Inside PopulateddlSubDepartments, var query's select...just select d and return that as json
If I just select d in my controller it returns in my alert "[object Object]". I believe I need that select statement to select both of those columns.
0

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']));

3 Comments

THAT WORKS! Thank you! If you have time I need my function to do two more things. I need to clear ddlSubDepartments options each time the function is ran, and also, it is only working for a Json with one set of values. Like {"value":5,"name":"SubDepartment1"},{"value":8,"name":"SubDepartment1"} doesn't work since there are two sets.
Also, would it be better for me to just change my controller where it looks like {value: 5, ...} from the start? Then I wouldn't even have to parse it?
Do you know why it is only working for selections with one data point?
0

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.');
        }
      });
    }
  });
});

1 Comment

This is a great answer and a great method for doing this. However, due to simplicity I accepted the other one. Thank you so much though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.