Displaying a list of objects in asp.net mvc
I am new to MVC. I am developing a web application in asp.net MVC. I have a form through which users can register after the registration user is redirected to the ProfileView.aspx page. so far everything is fine here.
Now I want to show the titles of articles posted by this user right below their profile. Right now I am using the following code:
public ActionResult ProfileView(int id)
{
Profile profile = profileRepository.GetProfileByID(id);
var articles = articlesRepository.FindArticlesByUserID(id).ToList();
return View("ProfileView", profile);
}
Thanks for the help in advance Baljit Grewal
a source to share
I can imagine two options:
Use a ViewData dictionary to store 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. ViewModel is a data transfer object. You can 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 will have to copy the values from your model to the ViewModel to your controller .:
public class ProfileViewModel
{
public int Id{ get; set; }
public string Name { get; set; }
.......
public IList<Article> Articles { get; set; }
}
If you get to this last option, have a look at AutoMapper (Object Mapping Object).
a source to share