jeudi 27 août 2015

Binding ViewModel with a list of ViewModels including HttpPostedFileBase to controller action

Okay, so i'm gonna try my best to explain the problem i'm facing at the moment.

I want to have a create view, which is strongly typed to a ViewModel. The ViewModel has some properties, where one of them is a list, containing ViewModels of another kind. That ViewModel contains some more properties, plus a value of type HttpPostedFileBase.

The createView should contain a file input for each of the viewModels, in the List. All other properties are going to be hidden from the user. The only thing that needs user interaction is the HttpPostedFileBase.

The thing is, firstly, i cannot get EditorFor to create a file input, and believe me lord iv'e tried. Secondly, i need to do it for every entry in the list of the strongly typed viewModel (TestViewModel below), so it can bind the values back to the controller on post.

The reason im creating this, as a test project, is that i need to see what the HTML would look like, in order for the binder to be able to bind it to the controller post action.

Please, if you dont understand the problem above, feel free to ask questions. I will do my best to answer. Thanks !

Simplified example classes.

public class TestViewModel
    public string SomeString { get; set; }
    public int SomeInt { get; set; }
    public List<ImageViewModel> ImageViewModels { get; set; }

public class ImageViewModel
    public HttpPostedFileBase Value { get; set; }

Create View (simplified, i know. It's a test project)

@model WebApplication1.Models.TestViewModel

    ViewBag.Title = "Create";


@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                @for (int i = 0; i < Model.ImageViewModels.Count; i++)
                    <td>@Html.EditorFor(m => m.ImageViewModels[i].Value)</td>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />

    @Html.ActionLink("Back to List", "Index")

@section Scripts {

Aucun commentaire:

Enregistrer un commentaire