Santosh Navle
Santosh Navle

Reputation: 65

MVC 4 | Kendo UI | Dropdownlist Change event

I have KendoUI Dropdownlist placed inside the Kendo Grid and i am able to set the change event on the dropdown list using the code below

function onDropDownChanged(e) {    
        var text = $("#TestMethodId").data("kendoDropDownList").value();
        alert(text);    
    }

using the code above 1. how would i be able to access the ViewBag content like 'ViewBag.Test'? 2. I need to iterate through the values inside the ViewBag and set one of the textbox property in the grid to the value from that viewbag.

Upvotes: 1

Views: 4869

Answers (1)

Andrei V
Andrei V

Reputation: 7486

The short answer is: you can't. You are trying to mix client-side processing with server-side processing. This is simply not possible.

The onDropDownChanged function will execute after an action preformed by the user. This means that the Razor engine has already parsed the .cshtml files and sent the HTML code to the client. This in turn means that any instruction containing the ViewBag object has already been executed.

Now, I don't really know what your ViewBag contains. Therefore, I'll make the assumption that you have stored some strings (values) and that the property names are stored as options in the dropdownlist. You probably want to access the data in the ViewBag, based on what you select in the dropdownlist. In that case, you should do the following:

  1. In your controller, create a dictionary with the keys being the values of your dropdownlist and the values, whatever you need; save this dictionary in the ViewBag
  2. In your view, convert the dictionary to a JSON string, and parse it client side to get an object with the same keys
  3. In the onDropDownChanged event, just access this object using the select text to get the desired value.

Your question is a bit vague, therefore I cannot be 100% certain that this is what you need. The bottom line is, you can't mix server-side and client-side code in that way. You need to rely on tricks.

EDIT: Here is a trick that could help you. In your view, serialize the ViewBag and save the value to a JavaScript variable; parse the text into an object; you can now iterate it using JavaScript.

<script>
     var tmpViewBag = '@Html.Raw(Json.Encode(ViewBag.MyObject))'; //notice I'm using ' and not "
     var myOptions = [];

     $(document).ready(function() {
          myOptions = JSON.parse(tmpViewBag); //you now have the object array
     })
</script>   

Inside the select event you can now use the object array as follows:

function onDropDownChanged(e) {    
    var text = $("#TestMethodId").data("kendoDropDownList").value();
    //alert(text);    

    for (var i = 0; i < myOptions.length; i++) {
        if (myOptions.TestName === text) { //it can as well be ".TestId"
            $("#mytextbox").value(myOptions.PassThreshold); //you can set whatever you want
            break;
        }
    }
}

Upvotes: 2

Related Questions