gpt4 book ai didi

.net - 模型类中定义的 ASP MVC HttpPostedFile

转载 作者:行者123 更新时间:2023-12-01 07:21:03 24 4
gpt4 key购买 nike

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

}

谢谢!

最佳答案

Is it necessary to create a custom model binder for these cases?



不,我建议您使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com