• js:Razor视图下服务器代码给Javascript变量赋值


    namespace Razor.Controllers
    {
        public class JSController : Controller
        {
            public ActionResult Index()
            {
                List<string> FriendsId = new List<string> { "S1", "S2", "S3", "S4" };
                ViewBag.FriendsId = FriendsId;
                return View();
            }
        }
    }
    @{
        ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    <script type="text/javascript">
    var array = new Array();
    @{   
     string message=""; 
    }
    @for (int i = 0; i < 3; i++) {
        message += "array[" + i + "]="" + ViewBag.FriendsId[i] + "";";
    }
    @MvcHtmlString.Create(message);
    alert(array[0]);
    </script>
    public class PersonModel
    
        {
    
            public string Name { get; set; }
    
            public int Age { get; set; }
    
        }
    static List<PersonModel> DummyData()
    
            {
    
                var data = new List<PersonModel>()
    
                               {
    
                                   new PersonModel()
    
                                       {
    
                                           Name = "Tom",
    
                                           Age = 20
    
                                       },
    
                                   new PersonModel()
    
                                       {
    
                                           Name = "Cat",
    
                                           Age = 5
    
                                       }
    
                               };
    
                return data;
    
            }
    public ActionResult Index()
    
            {
    
                var data=DummyData();
    
                return View(data);
    
            }
    <script >
    
            $(function() {
    
                var model = <%= new JavaScriptSerializer().Serialize(Model) %>;
    
                debugger;
    
            }) 
    
        </script>
    <script >
    
            $(function() {
    
                var model = <%= new JavaScriptSerializer().Serialize(Model) %>;
    
                alert(model[0].Name);
    
                debugger;
    
            }) 
    
        </script>
  • 相关阅读:
    Python学习笔记013_正则表达式
    Python学习笔记012_网络_异常
    Python学习笔记011_模块_标准库_第三方库的安装
    Python学习笔记010_迭代器_生成器
    PHP extract() 函数
    php 获取客户端IP
    php array_walk
    PHP array_map()
    PHP call_user_func
    类的更新----MVC设计模式
  • 原文地址:https://www.cnblogs.com/mrxiaohe/p/5169148.html
Copyright © 2020-2023  润新知