2

In My MVC 4 App i want to populate Html.LisboxFor with an Ajax result.

My View: @using (Html.BeginForm("UpdatePriority", "Priority", FormMethod.Post)) {

    @Html.Hidden("myListBoxValuesValues")

    <div class="row">

        <div class="col-md-2">
            <label>FA:</label>
            @Html.ListBoxFor(m => m.FA, new MultiSelectList(@Model.FA), new { @class = "lbx_FA" })
        </div>

        <div class="col-md-1">
            <input id="btnAdd" type="button" value="  > " onclick="addItem();" />
        </div>

        <div class="col-md-2">
            <label>CEID list:</label>
            @Html.ListBoxFor(model => model.CEIDs, new MultiSelectList(Model.CEIDs), new { @class = "lbx_CEIDs" })
        </div>

...and so on..

My my controller function (returns string of a json model):

public string getCeidPerFA(string FA)
        {
            return unitOfWork.ToolRequiredRepository.getCEIDsPerFA_Scenario(DAL.UnitOfWork.Scenario, FA);
        }

The repository function:

internal string getCEIDsPerFA_Scenario(string scenario, string FA)
        {
            //create the result list (FAs):

            List<string> FAs = FA.Split(',').ToList();

            var CEIDs = from row in context.ToolRequireds
                      where row.Scenario == scenario && FAs.Contains(row.FA)
                      select row.CEID;

            List<string> lst = CEIDs.Distinct().ToList();

            //create Json Result:

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

            foreach (var ceid in lst)
            {
                items.Add(new SelectListItem { Text = ceid, Value = ceid });
            }


            return Json.Encode(items);
        }

My Script:

   function addItem() {

    var result = "";

    var x = document.getElementById("FA");
    for (var i = 0; i < x.options.length; i++) {
        if (x.options[i].selected == true) {
            result += x.options[i].value + ",";
        }
    }

    result = result.substring(0, result.length - 1);

    $.ajax({

        url: "@(Url.Action("getCeidPerFA", "CeidSelection"))",

        data: { "FA": result },

        success: function (data) {


            if (data.length > 0) {
                JSON.pa
                $("#CEIDs").append(JSON.parse(data));
            }
            else
                alert("No Result");
        },

        error: function (xhr) {

            alert("Something went wrong, please try again");

        }

    });
}

My code is wrong but i have no idea how to do so. Any help will be very appreciated.

user3087881
  • 340
  • 4
  • 14

1 Answers1

3

loop through the data result like this

$('#CEIDs').empty();
$.each($(data), function(key, value) {
    $('#CEIDs').append('<option value=' + key + '>' + value + '</option>');
});
Matt Bodily
  • 6,403
  • 4
  • 29
  • 48
  • i changed my function to return a JsonResult. i'm creating the JsonResult like this: JsonResult js = new JsonResult() { Data = items, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; Then i'm using your code inside the ajax success. now all i see in the listbox is: "[object Object]". i can't see the actual values of the Json. – user3087881 Dec 18 '13 at 12:30
  • that tells me that you have the list item but not the value. If you look at the object using firebug you should be able to determine what name you need to look at. should be something like value.key and value.value, whatever names you have on those fields – Matt Bodily Dec 18 '13 at 14:38
  • Thx! it works. I used your tip and using the chrome developers tools a managed to debug the Json and to make the prorper adjustments. – user3087881 Dec 19 '13 at 11:48