MD Ghouse MD Ghouse - 1 month ago 7
C# Question

Cannot assign void to an implicitly-typed local variable when im converting class file into mvc controller

Here im creating Business class in Repo.cs and implementing this class in

HomeController.cs
but when i try to load its into
var x
('storing values in x')
its throwing an Error


Cannot assign void to an implicitly-typed local variable


Repo.cs

public void EditAssData(int id) {
var x = (from n in db.Accessors where n.Id == id select n }).FirstOrDefault();
}


HomeController.cs

public JsonResult EditData(int Id=0)
{
var x= objrepo.EditAssData(Id);
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Answer

EditAssData is a void method so it does not return anything. This causes the following assignment

var x = objrepo.EditAssData(Id);

to throw the error.

You method needs to have a return type otherwise you will not be able to use it to assign values when called.

public Accessor EditAssData(int id) {
    var x = (from n in db.Accessors where n.Id == id select n }).FirstOrDefault();
    return x;
}

And your controller needs to pass the value with the result.

public JsonResult EditData(int Id = 0) {
    var x = objrepo.EditAssData(Id);
    return new JsonResult(x, JsonRequestBehavior.AllowGet);
}