Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
good day, i want a <select> tag in a view to be loaded with <options> upon view load via json.


this is my model class
C#
public class Category
    {
        public List<string> ID = new List<string>();
        public List<string> Name = new List<string>();
        public List<string> lgaID = new List<string>();
        public List<string> lgaName = new List<string>();
    }


C#
this is my controller class method that i want to be called from json

C#
public ActionResult getLGA()
        {
            try
            {
                Category c = new Category();

                char[] chars = { ',' };

                testStealthServ.countries csd = new testStealthServ.countries();
                List<string> sth = csd.getlocal("2").ToList<string>();
                foreach (var v in sth)
                {
                    string[] splits = v.Split(chars);

                    c.lgaName.Add(splits.ElementAt(0));
                    c.lgaID.Add(splits.ElementAt(1));
                }

                return Json(c.lgaName, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

this method works as expected by giving me an array list. I think the issue is with the javascript/jquery call

I want my controller method to populate a <select> tag in the view below but that isn't working
C#
<select id="schllga" class="form-control-select" required></select>

JavaScript
<script language="javascript">
                            $.get("getLGA", null, BindData);
                            function BindData(custs)
                            {
                                var sel = $("#schllga");
                                for (var j = 0; j < custs.length; j++)
                                {
                                    var newOpt = "<option>" + custs[j].lgaName + "</option>";
                                    sel.append(newOpt);
                                }
                            }
                        </script>


I also tried this bt it doesn't work too
C#
<select id="schllga" class="form-control-select" required></select>

JavaScript
<script>
     $.get("@Url.Action("getLGA")", function(costs) {
           var $sel = $("#schllga");
           $sel.empty();
           for (var j = 0; j < custs.length; j++) {
               $("<option/>")
                   .text(custs[j].lgaName)
                   .appendTo($sel);
           }
     });
</script>


pls guide me as to where my mistake(s) are. Thanks
Posted
Comments
Anil Sharma1983 10-Jan-16 2:07am    
Please check your ajax request result in firfox browser or google chrome in net tab .
EasyHero 10-Jan-16 2:49am    
pls how do I do that?
Anil Sharma1983 10-Jan-16 3:23am    
install firbug plugin, then press F12 and check that net tab or F12 in google chrome and then check network tab under xhr request
[no name] 10-Jan-16 4:34am    
Where is the problem exactly, is it hitting your controller action(debug it) or it is hitting but not displaying anything.
EasyHero 15-Jan-16 1:37am    
its hitting and displaying the correct result from the controller code. the problem is from the javascript
i'm not very good in javascript so I don't know what to do there

1 solution

In code it uses $.get() and returns data in json format. So you are not getting correct data - use $.getJson instead of that.

Follow below steps to achieve the same:

Step 1: Controller Code
C#
public ActionResult getLGA()
{
	try
	{
		Category c = new Category();

		char[] chars = { ',' };

		testStealthServ.countries csd = new testStealthServ.countries();
		List<string> sth = csd.getlocal("2").ToList<string>();
		foreach (var v in sth)
		{
			string[] splits = v.Split(chars);

			c.lgaName.Add(splits.ElementAt(0));
			c.lgaID.Add(splits.ElementAt(1));
		}

		return Json(c.lgaName, JsonRequestBehavior.AllowGet);
	}
	catch (Exception ex)
	{
		throw ex;
	}
}

Step 2: Javascript Code
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
$.getJSON('@Url.Action("getLGA","ControllerName")', function(costs) {
   var $sel = $("#schllga");
   $sel.empty();
   $.each(costs, function(index, element) {		
		$("<option/>").text(element).appendTo($sel);
    });
});
</script>

Note: You need to put your controller name.
 
Share this answer
 
v3
Comments
EasyHero 12-Jan-16 13:34pm    
I tried this but it didn't work, still not returning anything but if I run my controller function, it returns what I need in a generic list in json format
EasyHero 15-Jan-16 1:45am    
are the function parameters index and element keywords or are they supposed to mean something in my code
[no name] 15-Jan-16 2:19am    
Did you follow properly what I answered. Because I am getting the result in dropdown using the answer. Just follow it - hope it will work for you..

Secondly are you missing jQuery reference. Just cross check it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900