0

I would like to pass through the viewbag the name of the value field and the text field to put in my dropdownlist. This my code:

<script type="text/javascript">

    var nameDDL = '@ViewBag.NameDDL';
    var dropdownId = '#' + nameDDL;
    var urlAction  = '@ViewBag.UrlAction';
    var keyField   = '@ViewBag.KeyField';
    var textField  = '@ViewBag.TextField';

    $(document).ready(
        function () {
            $(window).on("load",function () {
                $.ajax({
                    type: 'GET',
                    data: {
                        'EveID': $("#ddlEveType").val()
                        //'EveID': '1'
                    },
                    url: urlAction,
                    contentType: "application/json",
                    success: function (data) {
                        console.log(data);

                        $.each(data, function (i, item) {
                            $(dropdownId).append($('<option>', {
                                This doesn't work ??????
                                value: item. keyField ,
                                text: item. textField
                            }));
                        });    
                    }
                });
            });
        });
</script>

How to pass this parameters dynamcally from viewbag ?

Cicciux
  • 177
  • 4
  • 19

1 Answers1

0

I think you are having a problem because keyField is a string, rather than representing a property of an object.

Try this instead to get the keyField

item[keyField]

Here's the example of the JSON

{
    value: item[keyField] ,
    text: item[textField]
}

I'm using this as a point of reference, even though the question is slightly different:

Getting a Custom Objects properties by string var

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40