首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模型类中定义的ASP MVC HttpPostedFile

模型类中定义的ASP MVC HttpPostedFile
EN

Stack Overflow用户
提问于 2011-11-03 16:13:11
回答 1查看 6.1K关注 0票数 3

您可以将模型的属性定义为HttpPostedFile?我正在尝试,并且总是作为空值出现。这是代码

代码语言:javascript
复制
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; }
}

控制器

代码语言:javascript
复制
    [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)可以作为参数传递给控制器?

代码

代码语言:javascript
复制
    [HttpPost]
    public ActionResult Create(New obj, HttpPostedFileBase file)
    {

    }

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-03 16:16:04

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

不是的。我建议您使用HttpPostedFileBase而不是HttpPostedFile

代码语言:javascript
复制
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; }
}

然后是一个控制器:

代码语言:javascript
复制
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):

代码语言:javascript
复制
@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):

代码语言:javascript
复制
@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>
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7991809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档