Kaken
Kaken

Reputation: 163

ASP MVC HttpPostedFile defined in model class

You can define a property of the model as HttpPostedFile? I'm trying and always comes as a null value. This is the code

public class New
{
    public string Title { get; set; }

    public DateTime PublishDate { get; set; }

    [UIHint("File")]
    public Image ImageHeader { get; set; }

}

public class Image
{
    public string FooterText { get; set; }

    public HttpPostedFile File { get; set; }
}

Controller

    [HttpPost]
    public ActionResult Create(New obj)
    {
        // OK it's populated 
        string FooterText = obj.ImageHeader.FooterText;

        // Error it is not populated! always == null
        HttpPostedFile ImagenFile = obj.ImageHeader.File;

        return View();
    }

Is it necessary to create a custom model binder for these cases? Or just the objects(httppotedfile) can be passed as parameters to the controller?

Code

    [HttpPost]
    public ActionResult Create(New obj, HttpPostedFileBase file)
    {

    }

Thanks!

Upvotes: 3

Views: 6575

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

Is it necessary to create a custom model binder for these cases?

No. I would recommend you using HttpPostedFileBase instead of HttpPostedFile:

public class New
{
    public string Title { get; set; }

    public DateTime PublishDate { get; set; }

    [UIHint("File")]
    public Image ImageHeader { get; set; }

}

public class Image
{
    public string FooterText { get; set; }

    public HttpPostedFileBase File { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new New
        {
            Title = "some title",
            PublishDate = DateTime.Now,
            ImageHeader = new Image
            {
                FooterText = "some footer"
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(New model)
    {
        // everything will be properly bound here
        // see below for the views on how to achieve this
        return View(model);
    }
}

a corresponding view (~/Views/Home/Index.cshtml):

@model New

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(x => x.Title)
        @Html.EditorFor(x => x.Title)
    </div>
    <div>
        @Html.LabelFor(x => x.PublishDate)
        @Html.EditorFor(x => x.PublishDate)
    </div>
    <div>
        @Html.EditorFor(x => x.ImageHeader)
    </div>

    <input type="submit" value="OK" />
}

and the editor template (~/Views/Home/EditorTemplates/File.cshtml):

@model Image

<div>
    @Html.LabelFor(x => x.File)
    @Html.TextBoxFor(x => x.File, new { type = "file" })
</div>

<div>
    @Html.LabelFor(x => x.FooterText)
    @Html.EditorFor(x => x.FooterText)
</div>

Upvotes: 14

Related Questions