Question

I have an entity Movie that has 2 fields(poster and trailer) of varbinary(max) within the database. When I want to create the instance on the controller I had a lot of problem trying to get those fields from the View, finally, I got this solution:

[HttpPost]
public ActionResult Create([Bind(Exclude = "poster, trailer")]Movie movie, HttpPostedFileBase poster, HttpPostedFileBase trailer)

Any one has a better solution for this binding, just to get something like this?:

public ActionResult Create(Movie movie)

I need "poster" and "trailer" fields that they come with the post action too

Was it helpful?

Solution

Use a view model

public class MovieModel
{
    public HttpPostedFileBase Poster { get; set; }
    public HttpPostedFileBase Trailer { get; set; }
}

The in your controller

[HttpGet]
public ActionResult Create()
{
    return View(new MovieModel());
}

[HttpPost]
public ActionResult Create(MovieModel movie)
{
    var entity = new Movie();

    using (var memoryStream = new MemoryStream())
    {
        movie.Poster.InputStream.CopyTo(memoryStream);
        entity.Poster = memoryStream.ToArray();
    }

    using (var memoryStream = new MemoryStream())
    {
        movie.Trailer.InputStream.CopyTo(memoryStream);
        entity.Trailer = memoryStream.ToArray();
    }

    dbContext.Movies.AddObject(entity);
    return View("index");
}

OTHER TIPS

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top