Passing list from MVC ViewBag to JavaScript

前端 未结 3 1432
执念已碎
执念已碎 2021-02-02 16:57

I have a list of users which I pass from my controller to my view using the view bag. Now I need to be able to pass the same list to the javascript on the page. I could reconstr

3条回答
  •  囚心锁ツ
    2021-02-02 18:01

    @Darin Dimitrov answer is spot on. I would just like to add to it if anyone is passing a model and not a viewbag.

    
    

    viewmodel

    public class YourViewModel
      {
        public IEnumarable YourPocos { get; set; }
      }
    

    Controller

    public class YourController : Controller
    {
        public ActionResult Index()
        {
            YourViewModel vm = new YourViewModel{
                // Using Dependancy injection
                YourPocos = yourRepo.GetYourPocos();
            };
            return View("Index", "_Layout",vm);
        }
    }
    

    I realise this answer might be redundant, but it is the first time i am using Json.Encode and passing model values to a jquery extension. This for me is too cool. It does to a certain degree create massive extensibility on what would otherwise be an @htmlhelper

提交回复
热议问题