MVC後台資料賦值給前端JS對象

來源:互聯網
上載者:User

標籤:多個   tab   技術分享   from   ajax   對象傳遞   ber   alt   cti   

方式一:

reportInfo是後台Controller傳到前台的一個對象,其中包含多個屬性

js中使用:

 

方式二:

Controller中的資料,不管是使用的是ViewModel 還是ViewBag.Data,要將他傳遞到View中,這個很容易,但是如果要將它傳遞給JS中的某個對象,這個改如何處理呢?

背景資料格式:

12345678 public class ViewModel{    public int ID { get; set; }     public string Name { get; set; }     public List<string> Data { get; set; }}

Controller 傳遞到View的資料:

123456789101112 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 中的一個對象

12345 var viewModel = {    id: 0,    name: ‘‘,    data:[]}

  

1. 如果需要傳遞整形數字到JS中 

12345 <script>        [email protected];        or        [email protected];</script>

2.  如果需要傳遞字串到JS中

12345 <script>               viewModel.name=‘@ViewBag.Name‘;        or        viewModel.name=‘@Model.Name‘; </script> 

3.如果需要傳遞複雜的資料類型到JS中,如對象,數組,集合等,

123 <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

其中方式二轉載至:http://www.cnblogs.com/akwwl/p/5238975.html

MVC後台資料賦值給前端JS對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.