ASP MVC HttpPostedFile, определенный в классе модели - PullRequest
3 голосов
/ 03 ноября 2011

Вы можете определить свойство модели как 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 HttpPostedFile File { get; set; }
}

Контроллер

    [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();
    }

Нужно ли создавать для этих случаев настраиваемое связующее для моделей? Или просто объекты (httppotedfile) могут быть переданы в качестве параметров в контроллер?

код

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

    }

Спасибо!

1 Ответ

14 голосов
/ 03 ноября 2011

Необходимо ли для этих случаев создавать пользовательское связующее для моделей?

Нет.Я бы рекомендовал вам использовать HttpPostedFileBase вместо 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; }
}

, затем контроллер:

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);
    }
}

соответствующий вид (~/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" />
}

и шаблон редактора (~/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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...