码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-01-29 19:36:04      阅读:491      评论:0      收藏:0      [点我收藏+]

标签:

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>

 

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

标签:

原文地址:http://www.cnblogs.com/mrxiaohe/p/5169148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!