Reputation: 595
I am new to mvc and cannot figure out how to pass a single column of data to the view.
I have connected my db with ado.net entity model to models.
Then in my controller I have :
public class HomeController : Controller
{
shdesignEntities2 _db;
public ActionResult Index()
{
_db = new shdesignEntities2();
ViewData.Model = _db.tblKategoris.ToList();
return View();
}
}
In the view :
@foreach(var m in ViewData.Model)
{
<p>Kategori Ad :</p><p> @m.kategori_ad </p>
}
When I do like this , I pass the whole table data to the view where I only need a single column of information.
How can I only pass data from the column kategori_ad ?
Upvotes: 1
Views: 1519
Reputation: 1139
You may look at ViewModels. Also by this way you can use smaller part of data exposed.
For example
public class KategoriViewModel
{
public IEnumerable<Kategori> Kategoriler { get; set; }
}
Then you should add a controller action like
public ActionResult Something()
{
var model = new KategoriViewModel;
model.Kategoriler = your query..;
return View(model);
}
In view
@model KategoriViewModel
@foreach(var m in ViewData.Model)
{
<p>Kategori Ad :</p><p> @m.kategori_ad </p>
}
Upvotes: 0
Reputation: 101731
Use Select:
ViewData.Model = _db.tblKategoris.Select(x => x.kategori_ad).ToList();
Upvotes: 2
Reputation: 4809
In Controller
ViewData["Rows"] = (from c in _db.tblKategoris
select c.kategori_ad).ToList();
View
@foreach(var m in (List<string>)ViewData["Rows"])
{
<p>Kategori Ad :</p><p> @m </p>
}
Upvotes: 0
Reputation: 1519
You can use LINQ to find the object that you want and then pass it to the view, do something like this:
public ActionResult Index()
{
_db = new shdesignEntities2();
ViewData.Model = _db.tblKategoris.Select(x => x.kategori_ad).ToList();
return View();
}
That way ViewData.Model
only has the object that matches the linq query.
Here you can find more about Linq to retrieve data from a collection in C#: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
Upvotes: 0