Search code examples
ajaxasp.net-mvcviewreturn-valueviewbag

how to return multiple variable with jsonresult in mvc from controller to view?


in below code, i pass two parameters one is a list and second is viewbag message, but in view, side can't use viewbag.
So how to use it, please anyone help me
enter image description here


in view

enter image description here

where to i place viewbag message


Solution

  • As far as I understand to your question, you should create new class that holds both your list and message (instead of passing that to ViewBag).

    public class YourResponse
    {
        public string Message { get; set; }
        public List<SomeContent> Content { get; set; }
    }
    

    Then in your action in controller, create a new instance of this class and fill in the values and pass this instance back to the client.

    public ActionResult YourActionName()
    {
        // do the stuff here to get message and list
        var response = new YourResponse
        {
            Message = message, //insert your message here
            Content = list //and list of data here
        }
        return Json(response);
    }
    

    And finally read and use the data from server within client code.

    function OnSuccessed(data)
    {
        var message = data.Message;
        var list = data.Content;
        // you can work with message and list here
    }
    

    Just note that this is raw example, I have not run the code.