自定义数据绑定
新建自定义数据模型
public class FileCollectionModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
if (controllerContext == null) {
throw new ArgumentNullException("controllerContext");
}
if (bindingContext == null) {
throw new ArgumentNullException("bindingContext");
}
List<HttpPostedFileBase> files = GetFiles(controllerContext.HttpContext.Request.Files, bindingContext.ModelName);
if (files.Count == 0) {
return null;
}
switch (GetCollectionType(bindingContext.ModelType)) {
case CollectionType.Array:
return files.ToArray();
case CollectionType.Collection:
return new Collection<HttpPostedFileBase>(files);
case CollectionType.List:
return files;
default:
throw new InvalidOperationException(String.Format(
CultureInfo.CurrentUICulture, "This model binder does not support the model type '{0}'.", bindingContext.ModelType.FullName));
}
}
private static HttpPostedFileBase ChooseFileContentOrNull(HttpPostedFileBase theFile) {
bool fileContainsContent = (theFile.ContentLength != 0 || !String.IsNullOrEmpty(theFile.FileName));
return (fileContainsContent) ? theFile : null;
}
private static CollectionType GetCollectionType(Type targetType) {
if (targetType == typeof(IEnumerable<HttpPostedFileBase>) || targetType == typeof(HttpPostedFileBase[])) {
return CollectionType.Array;
}
if (targetType == typeof(ICollection<HttpPostedFileBase>) || targetType == typeof(Collection<HttpPostedFileBase>)) {
return CollectionType.Collection;
}
if (targetType == typeof(IList<HttpPostedFileBase>) || targetType == typeof(List<HttpPostedFileBase>)) {
return CollectionType.List;
}
return CollectionType.Unknown;
}
private static List<HttpPostedFileBase> GetFiles(HttpFileCollectionBase fileCollection, string key) {
// first, check for any files matching the key exactly
List<HttpPostedFileBase> files = fileCollection.AllKeys
.Select((thisKey, index) => (String.Equals(thisKey, key, StringComparison.OrdinalIgnoreCase)) ? index : -1)
.Where(index => index >= 0)
.Select(index => fileCollection[index])
.ToList();
if (files.Count == 0) {
// then check for files matching key[0], key[1], etc.
for (int i = 0; ; i++) {
string subKey = String.Format(CultureInfo.InvariantCulture, "{0}[{1}]", key, i);
HttpPostedFileBase thisFile = fileCollection[subKey];
if (thisFile == null) {
break;
}
files.Add(thisFile);
}
}
// if an <input type="file" /> element was rendered on the page but the user did not select a file before posting
// the form, null out that entry in the list.
List<HttpPostedFileBase> filteredFiles = files.ConvertAll((Converter<HttpPostedFileBase, HttpPostedFileBase>)ChooseFileContentOrNull);
return filteredFiles;
}
public static void RegisterBinder(ModelBinderDictionary binders) {
FileCollectionModelBinder binder = new FileCollectionModelBinder();
binders[typeof(HttpPostedFileBase[])] = binder;
binders[typeof(IEnumerable<HttpPostedFileBase>)] = binder;
binders[typeof(ICollection<HttpPostedFileBase>)] = binder;
binders[typeof(IList<HttpPostedFileBase>)] = binder;
binders[typeof(Collection<HttpPostedFileBase>)] = binder;
binders[typeof(List<HttpPostedFileBase>)] = binder;
}
private enum CollectionType {
Array,
Collection,
List,
Unknown
}
使用方式
public ActionResult ProcessFiles([ModelBinder(typeof(FileCollectionModelBinder))] IList<HttpPostedFileBase> files)
//public ActionResult ProcessFiles( IList<HttpPostedFileBase> files)
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength != 0)
{
string[] filesplit = file.FileName.Split( '//' );
string fileName = filesplit[filesplit.Length - 1];
file.SaveAs(Server.MapPath(@"/Images/") + fileName);
}
}
return RedirectToAction("ImageList");
}
public ActionResult ImageList()
{
var model = Directory.GetFiles(Server.MapPath(@"/Images/")).AsEnumerable ();
return View(model);
}
在index页面
<<p>
可以批量上传照片到指定目录,然后显示照片列表。
</p>
<% using( var form = Html.BeginForm(
"ProcessFiles",
"Home",
FormMethod.Post,
new { enctype = "multipart/form-data"}))
{%>
<p>
<input type="file" name="files" />
<br/>
<input type="file" name="files" />
<br/>
<input type="file" name="files" />
</p>
<input type="submit" value="批量上载照片" />
<% }%>
<% =Html.ActionLink ("照片列表","ImageList") %>
在ImageList页面
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<string>>" %>
<% foreach (string fileName in Model.ToList ()) { %>
<img src ="<% =fileName %>" alt ="image" width="150" height="100"/>
<% } %>
自定义数据绑定
最新推荐文章于 2022-01-28 15:18:58 发布