Grewal
Grewal

Reputation: 31

Showing a list of objects in asp.net mvc

I am new to MVC. I am developing an web application in asp.net MVC. I have a form through which users can get registered, after registration user redirected to ProfileView.aspx page. till here everything is fine.

Now I want to show the articles headings posted by that user right under his profile. Right now I m using following code:

public ActionResult ProfileView(int id)
{

Profile profile = profileRepository.GetProfileByID(id);

var articles = articlesRepository.FindArticlesByUserID(id).ToList();

return View("ProfileView", profile);

}

Thanks for helping in advance
Baljit Grewal

Upvotes: 0

Views: 665

Answers (2)

Ariel Popovsky
Ariel Popovsky

Reputation: 4875

I can think of two options:

Use the ViewData dictionary to store the articles.

public ActionResult ProfileView(int id)
{

Profile profile = profileRepository.GetProfileByID(id);  
var articles = articlesRepository.FindArticlesByUserID(id).ToList();
ViewData["Articles"] = articles;
return View("ProfileView", profile);
}

Or, if you want to avoid using ViewData, create a ViewModel. A ViewModel is kind of a data transport object. You could create a ProfileViewModel class like this:

public class ProfileViewModel
{
     public Profile Profile{ get; set; }
     public IList<Article> Articles { get; set; }
}

or just include the Profile properties you are using in your view, this will make binding easier but you'll have to copy values from your Model to your ViewModel in your controller.:

public class ProfileViewModel
{
     public int Id{ get; set; }
     public string Name { get; set; }
     .......
     public IList<Article> Articles { get; set; }
}

If you go for this last option take a look at AutoMapper (an object to object mapper).

Upvotes: 1

eazel7
eazel7

Reputation:

you will want your page to inherit from ViewPage and then you can use your model inside the .aspx markup like

Upvotes: 0

Related Questions