您可以将模型的属性定义为 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; }
}

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

是否有必要为这些情况创建自定义模型绑定(bind)器?或者只是对象(httppotedfile)可以作为参数传递给 Controller ​​?

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

    }

谢谢!

最佳答案



不。我建议您使用 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; }
}

然后是一个 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);
    }
}

相应的 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" />
}

和编辑器模板( ~/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>

关于.net - 在模型类中定义的 ASP MVC HttpPostedFile,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7991809/

10-09 17:47