Is there a way to update a ViewModel in MVC2?

Posted by Juvaly on Stack Overflow See other posts from Stack Overflow or by Juvaly
Published on 2010-03-02T01:19:38Z Indexed on 2010/04/03 6:53 UTC
Read the original article Hit count: 546

This code works:

[HttpPost]
public ActionResult Edit(int id, FormCollection fc)
{
    Movie movie =
        (
            from m in _ctx.Movie.Include("MovieActors")
                where m.MovieID == id select m
        ).First();
    MovieActorViewModel movieActor = new MovieActorViewModel(movie);

    if (TryUpdateModel(movieActor))
    {
        _ctx.ApplyPropertyChanges(movieActor.Movie.EntityKey.EntitySetName,
            movieActor.Movie);
        _ctx.SaveChanges();
    }

    return View(movieActor);
}

However, I am not sure how to test this, and in general would much rather have the method take a typed model like:

[HttpPost]
public ActionResult Edit(MovieActorViewModel movieActor)

Is this possible? What changes to my MovieActorViewModel class do I need to make in order to enable this? That class looks like this:

public class MovieActorViewModel
{
    public Movie Movie { get; set; }
    public Actor Actor { get; set; }

    public PublisherDealViewModel(Movie movie)
    {
        this.Movie = movie;
        this.Actor =
            (
                from a in this.Movie.Actors
                    where a.ActorID == 1 select a
            ).First();
    }
}

The view is typed (inherits ViewPage) simple:

<% using (Html.BeginForm()) {%>
    Movie Title: <%= Html.TextBoxFor(model=>model.Movie.Title) %><br/>
    Actor Name: <%= Html.TextBoxFor(model=>model.Actor.Name) %>
<% } %>

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about asp.net-mvc-2