How can I pass @Model to Angular ng-init

后端 未结 3 1125
我在风中等你
我在风中等你 2020-12-09 06:50

Isn\'t it possible to pass @Model to ng-init in ASP.NET MVC 4 view? When I do it like data-ng-init=init(@Model) it is undefined in the init()

相关标签:
3条回答
  • 2020-12-09 07:31

    inlcude the @using ProjectApp.Models then data-ng- init="init(@Newtonsoft.Json.JsonConvert.SerializeObject(Model))"

    0 讨论(0)
  • 2020-12-09 07:33

    Serialize you model into json string, using Newtonsoft.Json assembly or similar and pass the serialization result to data-ng-init.

    0 讨论(0)
  • 2020-12-09 07:50

    As I commented, you need to translate between your server-side objects (e.g. @Model) and client-side objects.

    For example, if you just wanted to use the Name property of @Model you could do something like this:

    <div ng-init="init('@Model.Name')"></div>
    
    $scope.init = function(name){
        console.log(name); // prints value of name
    }
    

    Notice, that even in this simple example, it is necessary to format @Model.Name into a JavaScript string (by putting quotes around it).

    Probably, you don't want to use the entire @Model object. It is best to choose only the fields you want and pass them in individually.

    If you need access to a lot of data from the server, it is recommended to use $http service and make a server call for the data.

    0 讨论(0)
提交回复
热议问题