[RESOLVED]Passing model to javascript

I am passing the model to a javascript function from a dropdown list OnChange event. But the model is always null and the javascript function never gets executed.

@Html.EnumDropDownListFor(m => m.VehicleType, new { onchange = string.Format("enablePassengerCount({0})", Model) })

function enablePassengerCount(model) {
                //check the value and use
                alert("test");

                if (model.VehicleType == "Car") {
                    passengerCount.showElement();
                    passengerCountLabel.showElement();
                }
                else
                {
                    passengerCount.hideElement();
                    passengerCountLabel.hideElement();
                }
                    
            };

Hi preetahb,

In my opinion, you can’t do that. I suggest that you could covert model data to JSON string, then use the JSON object in the JS function.

To convert model data to JSON string, please use JavaScriptSerializer:

 var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string objJson=serializer.Serialize(Model);

To convert JSON string to JSON object:

var obj =JSON.parse(JSonString);

Best Regards

Starain

try something like below, instead of passing the whole model and validating the property inside the javascript. i will pass the property value directly to javascript.

new { onchange = "enablePassengerCount('@Model.VehicleType')" })

function enablePassengerCount(vehicleType) {
                //check the value and use
                alert("test");

                if (vehicleType == "Car") {
                    passengerCount.showElement();
                    passengerCountLabel.showElement();
                }
                else
                {
                    passengerCount.hideElement();
                    passengerCountLabel.hideElement();
                }
                    
            };

Hi,

More specifically, use "view source" and you’ll likely see that what is rendered is the model type name (that is Model.ToString()) You can’t "write" the model directly to the browser text output and expect it to be usable by JavaScript.

So as answered above either you’ll have to recreate the model in JavaScript using the serializer or you could just pass the property you need as text.

Leave a Reply