您的位置:首页 > Web前端

MVC后台数据赋值给前端JS对象

2016-03-10 22:36 507 查看
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

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: