ASP MVC HttpPostedFile在模型类中定义

时间:2011-11-03 08:13:11

标签: .net asp.net-mvc asp.net-mvc-3

您可以将模型的属性定义为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 个答案:

答案 0 :(得分:14)

  

是否有必要为这些案例创建自定义模型绑定器?

没有。我建议您使用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>