Reputation: 73
I am building my first ASP.Net MVC based app and have a problem accessing the results of a linq to sql query in one of my views.
Here is my controller:
public ActionResult Details(int id)
{
var dataContext = new BuffetSuppliersDBDataContext();
var supplier = from m in dataContext.BO_Suppliers
where m.SupplierID == id
select m;
return View(supplier);
}
How can I access the supplier.SupplierName property in my view page, I have seen examples using a foreach loop and casting ViewData.Model to IEnumerable but there is not much point in using a loop as i am only returning one row.
Upvotes: 3
Views: 5322
Reputation: 532765
Choose the first object then use it as your model. A strongly-typed view (.e.g., ViewPage<Supplier>) will make it trivial to access the model properties.
var dataContext = new BuffetSuppliersDBDataContext();
var supplier = (from m in dataContext.BO_Suppliers
where m.SupplierID == id
select m).FirstOrDefault();
ViewData.Model = supplier;
return View();
With a view page defined as
public class Details : ViewPage<Supplier>
{
}
and in the view using
<label for="SupplierName" class='details-label'>Supplier Name:</label>
<span class='details-data'> <%= ViewData.Model.Name %> </span>
Upvotes: 3