js:Razor视图下服务器代码给Javascript变量赋值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
以上是关于js:Razor视图下服务器代码给Javascript变量赋值的主要内容,如果未能解决你的问题,请参考以下文章