Reputation: 137
I am working on Visual C# MVC project. I am using EF databse first approach in my model.My project is about developing an appmarket where users can buy apps. I used partial view in home page which will contain details of different apps in different partial views.Like App1 in 1st partial view, App2 in 2nd partial view, so on. For this I used for each loop.
In each partial view there is link called MoreInfo, so when user clicks on that they will go inside MoreInfo page. In database I have fields such as app info, app cost, description etc which will be displayed inside MoreInfo page. All these fields are in one table called Apps table.
When i follow Enumerable.FirstOrDefault approach I am able to retrieve only first record from database. But now my problem is I need to retrieve first record in my first MoreInfo view, second record in second MoreInfo view and so on.
My code for controller is :
public ActionResult MoreInfo()
{
var e = Enumerable.FirstOrDefault(db.AppmarketApps);
return View(e);
}
and in view i used :
@model Market.Models.AppmarketApp
<h3><span class="grey"><a href="#">MARKETPLACE</a> ›</span> @Model.Description</h3>
So here I am getting first record description for all MoreInfo views which I don't want. Thanks in advance.
Upvotes: 2
Views: 2034
Reputation: 137
Finally after playing with my code I got to know solution for this.
Before I had two controllers called HomeController and MoreInfoController. But since MoreInfo link was in Homepage itself, I removed MoreInfo controller and added code to HomeControoler itself. Here is the code which i add :
public ActionResult MoreInfo(short id)
{
var e = db.AppmarketApps.Where(x => x.ID == id).FirstOrDefault();
return View(e);
}
Here I am passing id as parameter and capital 'ID' is my primary key.Since i wanted to display only one record per view, i used FirstOrDefault method.
After this in my view I changed code like this :
@Html.ActionLink("MoreInfo", "MoreInfo", new { id = item.ID }, new { @class = "greyButton" })
Here first parameter "MoreInfo" is LinkName and Second parameter "MoreInfo" is link. As you can see when user clicks on MoreInfo link, id will be passed to that link by using
new { id = item.ID }.
class is used for style purpose. To be clear what above code does is, it will pass id to MoreInfo link and will display data present in AppmarketApps table.
Finally i used @Model.Name in my view if i wanted to display 'Name' and I used @Model.Description if i wanted to display 'Description' and so on.
Thanks to all who helped me in this.
Upvotes: 0
Reputation: 8147
Expanding on my comment you should use the ID of the application and then pass that into MoreInfo
so something like this:
public ActionResult MoreInfo(int id)
{
var e = db.AppmarketApps.Where(x => x.ID == id).FirstOrDefault();
return View(e);
}
Upvotes: 3
Reputation: 3199
Pass the Id of the app of interest in the link to MoreInfo and query your data based on that id.
Upvotes: 2