Необходимо ли для этих случаев создавать пользовательское связующее для моделей?
Нет.Я бы рекомендовал вам использовать 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>