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>

 

转载于:https://www.cnblogs.com/mrxiaohe/p/5169148.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值