The MVC background data is assigned to the front-end JS object, mvcjs

Source: Internet
Author: User

The MVC background data is assigned to the front-end JS object, mvcjs

Controller data, whether it is ViewModel or ViewBag. it is easy to pass Data to the View. But if you want to pass it to an object in JS, how can this problem be solved?

Background Data Format:

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

Data transmitted by the Controller to the 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);        } 

An object in front-end JS

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

  

1. If you need to pass an integer to JS

<script>        viewModel.id=@ViewBag.ID;        or        viewModel.id=@Model.ID;</script>

2. If you need to pass the string to JS

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

3. If you need to pass complex data types to JS, such as objects, arrays, and collections,

<script>        viewModel.data = @Html.Raw(Json.Encode(Model.Data));</script>

 

For more methods, see: http://stackoverflow.com/questions/3850958/pass-array-from-mvc-to-javascript

In addition to the JS object to the Controller, this direct use of Ajax, you can achieve, For details, see the http://stackoverflow.com/questions/16824773/passing-an-array-of-javascript-classes-to-a-mvc-controller

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.