Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a viewmodel object to a jquery variable

I need to access the members of viewmodel object in a javascript function and have tried to do this by assigning it to a jscript variable like this:

var teamEdit = (function() {
                return {
                    communityGroups: '@Model.CommunityGroups'
                }
            });


$(function() {
....
 var groups = teamEdit.communityGroups;

Unfortunately the groups variable comes out as undefined even though 'CommunityGroups' is defintely populated. (checked by debugging controller)

like image 413
BMills Avatar asked Jul 24 '26 18:07

BMills


1 Answers

@Model.CommunityGroups would simply call ToString() that would emit something like "System.Collections.Generic.List`1[CommunityGroup]".

You need to serialize it to JSON instead:

communityGroups: @Html.Raw(Json.Encode(Model.CommunityGroups))
like image 165
haim770 Avatar answered Jul 27 '26 12:07

haim770



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!