zoukankan      html  css  js  c++  java
  • MVC后台数据赋值给前端JS对象

    Controller中的数据,不管是使用的是ViewModel 还是ViewBag.Data,要将他传递到View中,这个很容易,但是如果要将它传递给JS中的某个对象,这个改如何处理呢?

    后台的数据格式:

        public class ViewModel
        {
            public int ID { get; set; }
    
            public string Name { get; set; }
    
            public List<string> Data { get; set; }
        }
    

    Controller 传递到View的数据:

            public ActionResult Index()
            {
                ViewBag.ID = 1;
                ViewBag.Name = "WWW";
                ViewModel viewModel = new ViewModel()
                {
                    ID = 100,
                    Name = "WWW",
                    Data = new List<string> {"A","B","C","D","E" }
                };
                return View(viewModel);
            } 

    前台JS 中的一个对象

        var viewModel = {
            id: 0,
            name: '',
            data:[]
        }
    

      

    1. 如果需要传递整形数字到JS中 

    <script>
            viewModel.id=@ViewBag.ID;
            or
            viewModel.id=@Model.ID;
    </script>
    

    2.  如果需要传递字符串到JS中

    <script>        
            viewModel.name='@ViewBag.Name';
            or
            viewModel.name='@Model.Name';  
    </script>  
    

    3.如果需要传递复杂的数据类型到JS中,如对象,数组,集合等,

    <script>
            viewModel.data = @Html.Raw(Json.Encode(Model.Data));
    </script>
    

    更多方法请参见:http://stackoverflow.com/questions/3850958/pass-array-from-mvc-to-javascript

    另外将JS 中的对象传递到Controller中,这个直接采用Ajax,就可以实现,详细请参见  http://stackoverflow.com/questions/16824773/passing-an-array-of-javascript-classes-to-a-mvc-controller

     

  • 相关阅读:
    存储过程
    .Net经典面试题
    《锋利的Jquery》
    WPF-1
    ios-5-类别和协议
    ios-4-创建单例模式
    ios-3-简单内存管理
    ios-2
    ios -1
    <<ASP.NET MVC4 Web编程>>笔记
  • 原文地址:https://www.cnblogs.com/akwwl/p/5238975.html
Copyright © 2011-2022 走看看