afridi shayed afridi shayed - 1 month ago 7
C# Question

How to convert void to implicitly local variable?

Here I'm writing logic in class file and implementing in a controller. When I'm trying to implement the code in the controller it's throwing an error as "cannot assign void to an implicitly-typed local variable"

public void Getass()
{
var xx = from n in db.Accessors
join cn in db.Countrys on n.CountryID equals cn.CountryID
select new
{
n.Name,n.Id,n.CountryID,
cn.CountryName};
}


Dummy.cs

public JsonResult tt()
{
var sss= objrepo.Getass();

return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Answer

Getass should return the collection but it is an anonymous type. Either create it in the method making the call

public JsonResult tt()
{
     var xx = from n in db.Accessors
              join cn in db.Countrys on n.CountryID equals cn.CountryID
              select new
              {
                 n.Name,
                 n.Id,
                 n.CountryID,
                 cn.CountryName
              };

    return Json(xx, JsonRequestBehavior.AllowGet);
}

or create a class to hold the result

public class MyModel {
    public string Name { get; set; }
    public string Id { get; set; }
    public string CountryID { get; set; }
    public string CountryName { get; set; }
}

public IList<MyModel> GetAccessors()
{
    var xx = from n in db.Accessors
             join cn in db.Countrys on n.CountryID equals cn.CountryID
             select new MyModel 
             {
                 Name = n.Name,
                 Id = n.Id,
                 CountryID = n.CountryID,
                 CountryName = cn.CountryName
             };
    return xx.ToList();
}

public JsonResult tt()
{
     var  sss=  objrepo.GetAccessors();

    return Json(sss, JsonRequestBehavior.AllowGet);
}
Comments