Kak*_*ken 3 .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; }
}
Run Code Online (Sandbox Code Playgroud)
调节器
[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();
}
Run Code Online (Sandbox Code Playgroud)
是否有必要为这些案例创建自定义模型绑定器?或者只是对象(httppotedfile)可以作为参数传递给控制器?
码
[HttpPost]
public ActionResult Create(New obj, HttpPostedFileBase file)
{
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Dar*_*rov 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; }
}
Run Code Online (Sandbox Code Playgroud)
然后一个控制器:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
相应的视图(~/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" />
}
Run Code Online (Sandbox Code Playgroud)
和编辑器模板(~/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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5518 次 |
最近记录: |