Reputation: 5705
Using the next code in my controller Index action, I try to display 2 fields contents in a razor view:
public class MyController : Controller
{
private MyEntities db = new MyEntities();
public ActionResult Index()
{
IEnumerable<Prod> signatures = from Prod in db.Products
select new Prod(Prod.ProductID, Prod.ProductName);
}
}
Previously I have created a class in the models folder and named it "Prod":
public class Prod
{
public int ProductID { get; set; }
public string ProductName { get; set; }
}
But when I run the project I fall in the next error:
MyProject.Controllers.MyController.Index()
not all code paths return a value
Any help please ?
Upvotes: 3
Views: 13241
Reputation: 9296
Sami-L, your Prod class does not have specialized constructor, that is, a constructor that accepts some initialization values. Your action should be something like this:
public ActionResult Index()
{
IEnumerable<Prod> signatures = from p in db.Products
select new Prod
{
ProductId = p.ProductID,
ProductName = p.ProductName
};
return View(signatures);
}
Note the curly braces "{" instead of "(" braces. This should help solve the constructor error which you are getting.
UPDATE: I've renamed a parameter in your LINQ query from Prod
to p
. Using Prod the way you specified made compiler think that your ProductID and ProductName were static properties. By renaming the parameter after from
this should help solve the issue.
Upvotes: 4
Reputation: 2003
You are missing the return
element. You will need to wrap this in a View
so that your Index razor view will be passed the Prod list.
public ActionResult Index()
{
IEnumerable<Prod> signatures = from Prod in db.Products
select new Prod(Prod.ProductID, Prod.ProductName);
return View(signatures); // add this
}
In the Index.cshtml you can also declare the model so the view is strongly typed, i.e.
@model IEnumerable<MyProject.Models.Prod>
<table>
@foreach(var prod in Model)
{
<tr>
<td>@prod.ProductID</td>
<td>@prod.ProductName</td>
</tr>
}
</table>
Upvotes: 3
Reputation: 67296
I think you are simply missing the return
statement.
public ActionResult Index()
{
IEnumerable<Prod> signatures = from Prod in db.Products
select new Prod(Prod.ProductID, Prod.ProductName);
return View(signatures); // this is missing
}
Upvotes: 3