pass List along with Json data as return type

arsar 121 Reputation points
2021-11-17T06:56:19.943+00:00

I have to pass List along with the object in Json returned method, how can I do that?
My method::

public JsonResult  GetByKey(int? id)  
{            
        List<string> message = new List<string>(); 
        message.Add("zone1");
        message.Add("zone2");
        message.Add("zone3");

        var data = (from z in db.FirmModels 
                    where z.FirmId == id
                    select z).ToList();
        return Json(data,  JsonRequestBehavior.AllowGet);

}

I have to pass the List message in the Json returned type. How can I do this?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,780 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,596 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,946 Reputation points Microsoft Vendor
    2021-11-17T07:41:08.56+00:00

    Hi @arsar ,

    You can create a new model which contains the string List and the Object list, code like this:

    public class ResultViewModel  
    {  
        public List<string> Message { get; set; }  
        public List<FirmModels> FirmModels { get; set; }  
    }  
    

    Then modify the GetByKey method as below:

        public JsonResult GetByKey(int? id)  
        {  
            List<string> message = new List<string>();  
            message.Add("zone1");  
            message.Add("zone2");  
            message.Add("zone3");  
    
    
            var data = (from z in db.FirmModels  
                        where z.FirmId == id  
                        select z).ToList();  
    
            var resulemodel = new ResultViewModel();  
            resulemodel.Message = message;  
            resulemodel.FirmModels = data;  
    
            return Json(resulemodel, JsonRequestBehavior.AllowGet);  
    
        }  
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.