tentmaking
tentmaking

Reputation: 2146

View Models with database

I am having trouble understanding and implementing a view model. For example, say I have a Blog object, where each Blog object represents one blog post. I have a view that contains a list of each blog (title, text, date posted, etc...). Currently I am passing a list of blog objects to the view, but I would rather pass a list of BlogViewModel objects to the view. How do I do it? Does anyone have any good resources that will help me understand View Models?

Edit The BlogViewModel I want to pass will contain abbreviated fields for the title and the text of the Blog. For example, I only want to show the first 10 characters of the title and the first 25 characters of the text.

Upvotes: 0

Views: 127

Answers (1)

glosrob
glosrob

Reputation: 6715

Assuming you are currently doing something like:

public ActionResult GetBlogs()
{
    var someService = new FooService();
    var blogs = someService.GetMeMyBlogs();
    return View("bloglist", blogs); 
}

To use view models you need to either return them from your service, or convert the objects in the controller before sending them on to the view.

One option is to create an extension method for the Blog object.

Say we have a few properties something like:

public class BlogVM
{
    public string Title {get;set;}
    public string Body {get;set;}
    public string AuthorName {get;set;}
    public int Id {get;set;}
}

We could write an extension method:

public static BlogVM ToBlogVM(this Blog source)
{
    return new BlogVM 
    {
         Title = source.Title.SubString(0, 10),
         Body = source.Body.SubString(0, 25),
         AuthorName = source.Author.Name,//assuming you have some kind of Author table, I'm sure you get the idea..
         Id = source.Id
    };
}

Now in your controller you can do something like

public ActionResult GetBlogs()
{
    var someService = new FooService();
    var blogs = someService.GetMeMyBlogs();
    return View("bloglist", blogs.Select(x => x.ToBlogVM())); 
}

Which passes a list of BlogVM objects to your view.

edit: probably worth adding a few words on why ViewModels.

  • why send the view everything if it doesn't need it? In your example, your body might be a big block of text. If you are only going to display 25 chars, only send it 25 chars

  • some of the info in the object might be sensitive. You might want to send the Author's name, but certainly not other information you might hold such as his name, email or even password or address.

  • similarly, in a POST scenario you can control what information can potentially be sent back to you. If you allow the user to POST back to a full object, they can potentially send you back updated fields you might not expect. If you use a VM, you can control what information you will accept.

  • I find it easier/quicker for building views

Upvotes: 2

Related Questions