Click here to Skip to main content
15,898,035 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to use Edit in MVC for multiple selection . So I've made a Jsonresult to fetch the Data for that Id :-

What I have tried:

C#
<pre>public JsonResult FetchDataForEdit()
        {
            int IDtoEdit = Convert.ToInt32(TempData["IDtoEdit"]);
            string MyTableName = Convert.ToString(TempData["MyTableName"]);
            
            try
            {
                Type tableType = typeof(CourseDesc);
                switch (MyTableName)
                {
                    case "CourseTbl":
                        tableType = typeof(CourseTbl);
                        break;
                    case "CourseDescTbl":
                        tableType = typeof(CourseDesc);
                        break;
                    case "CourseSubDesc":
                        tableType = typeof(CourseSubDesc);
                        break;
                    case "InternTbl":
                        tableType = typeof(InternShip);
                        break;
                    case "ContactTbl":
                        tableType = typeof(Contact);
                        break;
                }

                using (EBContext db = new EBContext())
                {
                    var results = new List<object>();
                    foreach (var item in db.Set(tableType))
                    {
                        //Want to Add result for selected IDtoEdit here
                        results.Add(item);
                    }

                    return new JsonResult { Data = results, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
                }

            }

            catch (Exception ex)
            {
                string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : "";
                return new JsonResult { Data = "Not Found", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }

        }
Posted
Updated 21-Aug-17 6:48am

1 solution

Assuming the IDtoEdit is the primary key of the entity, and you only want to return the matching item, use Find:
C#
using (var db = new EBContext())
{
    var results = new List<object>();
    var item = db.Set(tableType).Find(IDtoEdit);
    if (item != null) results.Add(item);
    
    return Json(results, JsonRequestBehavior.AllowGet);
}

DbSet.Find Method (Object[]) (System.Data.Entity)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900