CiccioMiami CiccioMiami - 5 months ago 56
Javascript Question

How to pass parameters to jQuery document.ready() function (ASP.NET MVC, C#)

I would like to pass a parameter to the jQuery document.ready() function from my View:

$(document).ready(function (parameter){
$('select[name=Product]').val(parameter);
});


How can I fire the event from my View and pass the parameter? I use Razor as View engine.

Thanks

Answer

You can't. The document.ready function doesn't take parameters. You could for example define this parameter as a global variable in your view:

<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
</script>

and then in your separate javascript file use this global variable:

$(function() {
    $('select[name=Product]').val(model.SomeProperty);
});
Comments