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