




下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、ASP.NET MVC4用法MongoDB制作相册管理_ 这篇文章主要介绍了ASP.NET MVC4用法MongoDB制作相册管理的相关资料,感爱好的小伙伴们可以参考一下 ASP.NET MVC4用法MongoDB制作相册管理实例分享 TIPS:1.Image转成Base64保存到mongodb字段 2.数据模型是嵌套的关联 首先定义Model层: public class Photo : IEquatablePhoto Required public string PhotoName get; set; Required public string PhotoDescription get;
2、 set; public string ServerPath get; set; public Photo() public Photo(string name, string desc) PhotoName = name; PhotoDescription = desc; public bool Equals(Photo other) return string.Equals(PhotoName, other.PhotoName); public interface IAlbumIterable bool HasNext(); Photo Current(); Photo Next(); p
3、ublic interface IPhotosAggregable IAlbumIterable GetIterator(); public class AlbumIterator : IAlbumIterable private Album collection; private int count; public AlbumIterator(Album album) collection = album; public Photo Current() if (count collection.Count) return collectioncount+; else throw new In
4、dexOutOfRangeException(); public bool HasNext() if (count collection.Count - 1) return true; else return false; public Photo Next() if (HasNext() return collection+count; else throw new IndexOutOfRangeException(); public class Album : IPhotosAggregable BsonId public ObjectId Id get; set; Required pu
5、blic string Name get; set; Required public string Description get; set; public string Owner get; set; public Photo TitlePhoto get; set; BsonDateTimeOptions(Kind = DateTimeKind.Local,Representation =BsonType.DateTime) public DateTime CreationTime get; set; public IListPhoto Pictures get; set; public
6、Album() Pictures = new ListPhoto(); TitlePhoto = new Photo(); public Album(string name, string owner, Photo pic) Name = name; Owner = owner; TitlePhoto = pic; Pictures = new ListPhoto(); TitlePhoto = new Photo(); public bool InsertPicture(Photo pic) if (!Pictures.Contains(pic) Pictures.Add(pic); ret
7、urn true; else throw new ArgumentException(); public bool InsertPictures(ListPhoto photos) foreach(var photo in photos) if (!Pictures.Contains(photo) Pictures.Add(photo); else throw new ArgumentException(); return true; public bool RemovePicture(Photo pic) Pictures.Remove(pic); return true; public i
8、nt Count get return Pictures.Count; public Photo thisint index get return Picturesindex; set Picturesindex = value; public IAlbumIterable GetIterator() return new AlbumIterator(this); Services层的MongoAlbumPerformer.cs和ServerPathFinder.cs代码如下: public class MongoAlbumPerformer protected static IMongoCl
9、ient client; protected static IMongoDatabase database; private static IMongoCollectionAlbum collection; private string collectionName; public MongoAlbumPerformer(string databaseName, string collectionName) client = new MongoClient(ConfigurationManager.ConnectionStringsmongoDB.ConnectionString); data
10、base = client.GetDatabase(databaseName); this.collectionName = collectionName; collection = database.GetCollectionAlbum(collectionName, new MongoCollectionSettings AssignIdOnInsert = true ); public void SetCollection(string collectionName) this.collectionName = collectionName; collection = database.
11、GetCollectionAlbum(collectionName); public void CreateAlbum(Album album) var document = new Album Name = album.Name, Owner = HttpContext.Current.User.Identity.Name, Description = album.Description, CreationTime = DateTime.Now, TitlePhoto = album.TitlePhoto, Pictures = album.Pictures ; collection.Ins
12、ertOne(document); public ListAlbum GetAlbumsByUserName(string username) var projection = BuildersAlbum.Projection .Include(a = a.Name) .Include(a = a.Description) .Include(a = a.TitlePhoto) .Include(a=a.CreationTime); var result = collection .Find(a = a.Owner = HttpContext.Current.User.Identity.Name
13、) .ProjectAlbum(projection).ToList(); return result; public Album GetPicturesByAlbumName(string albumName) var projection = BuildersAlbum.Projection .Include(a = a.Pictures); var result = collection .Find(a = a.Owner = HttpContext.Current.User.Identity.Name a.Name = albumName) .ProjectAlbum(projecti
14、on).FirstOrDefault(); return result; public void UpdateAlbumAddPhoto(string albumName, Photo photo) var builder = BuildersAlbum.Filter; var filter = builder.Eq(f = f.Name, albumName) builder.Eq(f = f.Owner, HttpContext.Current.User.Identity.Name); var result = collection.Find(filter).FirstOrDefault(
15、); if (result = null) throw new ArgumentException(No album of supplied name: 0, albumName); else var picture = new Photo PhotoName = photo.PhotoName, PhotoDescription = photo.PhotoDescription, ServerPath = photo.ServerPath, ; var update = BuildersAlbum.Update.Push(a = a.Pictures, picture); collectio
16、n.UpdateOne(filter, update, new UpdateOptions IsUpsert=true ); public void DeletePhotoFromAlbum(string albumName, string photoName) var builder = BuildersAlbum.Filter; var filter = builder.Eq(f = f.Name, albumName) builder.Eq(f = f.Owner, HttpContext.Current.User.Identity.Name); var result = collect
17、ion.Find(filter).SingleOrDefault(); if (result = null) throw new ArgumentException(No album of supplied name: 0, albumName); else var update = BuildersAlbum.Update .PullFilter(a = a.Pictures, BuildersPhoto.Filter.Eq(p = p.PhotoName, photoName); long count = collection.UpdateOne(filter, update).Match
18、edCount; public class ServerPathFinder public string GetBase64ImageString(HttpPostedFileBase file) string mime = Regex.Match(file.ContentType, (?=image/)w+).Value; byte bytes = new bytefile.ContentLength; file.InputStream.Read(bytes, 0, file.ContentLength); return string.Format(data:image/0;base64,1
19、,mime, Convert.ToBase64String(bytes); AlbumController.cs代码如下: public class AlbumController : Controller MongoAlbumPerformer mongod = new MongoAlbumPerformer(test,albums); HttpPost public ActionResult AlbumPreview(Photo model, HttpPostedFileBase file, string albumName, string delete, string phot) if
20、(delete = false) if (file != null) if (!file.ContentType.StartsWith(image) ModelState.AddModelError(file, 选择正确的格式照片!); else ServerPathFinder finder = new ServerPathFinder(); model.ServerPath = finder.GetBase64ImageString(file); if (ModelState.IsValid) mongod.UpdateAlbumAddPhoto(albumName, model); Mo
21、delState.Clear(); else mongod.DeletePhotoFromAlbum(albumName, phot); foreach(var error in ModelState.Values) error.Errors.Clear(); ViewBag.AlbumTitle = albumName; ViewBag.PhotoList = mongod.GetPicturesByAlbumName(albumName).Pictures; return View(); public ActionResult AlbumPreview(string Name) var a
22、lbum = mongod.GetPicturesByAlbumName(Name); ViewBag.AlbumTitle = Name; ViewBag.PhotoList = album.Pictures; return View(); HttpPost public ActionResult Create(Album model, HttpPostedFileBase file) if (!file.ContentType.StartsWith(image) ModelState.AddModelError(file, 选择正确的格式照片!); else ServerPathFinde
23、r finder = new ServerPathFinder(); model.TitlePhoto.ServerPath = finder.GetBase64ImageString(file); if (ModelState.IsValid) model.Owner = HttpContext.User.Identity.Name; mongod.CreateAlbum(model); var albums = mongod.GetAlbumsByUserName(HttpContext.User.Identity.Name); ViewBag.Albums = albums; retur
24、n View(); public ActionResult Create() var albums = mongod.GetAlbumsByUserName(HttpContext.User.Identity.Name); ViewBag.Albums = albums; return View(); 部分view视图: Create.cshtml ViewBag.Title = Create; h2我的相册/h2 Html.Partial(_MyAlbums, (ListAlbum)ViewBag.Albums) using (Html.BeginForm(Create, Album, Fo
25、rmMethod.Post, new enctype = multipart/form-data ) Html.AntiForgeryToken() div class=form-horizontal h4创建新相册: /h4 hr / Html.ValidationSummary(true, , new class = text-danger ) div class=form-group Html.LabelFor(model = model.Name, htmlAttributes: new class = control-label col-md-2 ) div class=col-md
26、-10 Html.EditorFor(model = model.Name, new htmlAttributes = new class = form-control ) Html.ValidationMessageFor(model = model.Name, , new class = text-danger ) /div /div div class=form-group Html.LabelFor(model = model.Description, htmlAttributes: new class = control-label col-md-2 ) div class=col-
27、md-10 Html.EditorFor(model = model.Description, new htmlAttributes = new class = form-control ) Html.ValidationMessageFor(model = model.Description, , new class = text-danger ) /div /div div class=form-group Html.LabelFor(model = model.TitlePhoto, htmlAttributes: new class = control-label col-md-2 )
28、 div class=col-md-10 input type=file name=file id=file style=width: 100%; data-val=true data-val-required=要求标题图片./ Html.ValidationMessage(file,new class = text-danger ) /div /div div class=form-group div class=col-md-offset-2 col-md-10 input type=submit value=Create class=btn btn-default / /div /div
29、 /div section scripts Scripts.Render(/bundles/jqueryval) script type=text/javascript $(img).click(function (data) ); /script AlbumPreview.cshtml ViewBag.Title = AlbumPreview; using (Html.BeginForm(AlbumPreview, Album, FormMethod.Post, new enctype = multipart/form-data) Html.AntiForgeryToken() Html.R
30、enderPartial(_Preview, (ListPhoto)ViewBag.PhotoList); div class=form-horizontal br / h4添加新的照片:/h4 hr / Html.ValidationSummary(true, , new class = text-danger ) div class=form-group Html.LabelFor(model = model.PhotoName, htmlAttributes: new class = control-label col-md-2 ) div class=col-md-10 Html.Ed
31、itorFor(model = model.PhotoName, new htmlAttributes = new class = form-control ) Html.ValidationMessageFor(model = model.PhotoName, , new class = text-danger ) /div /div div class=form-group Html.LabelFor(model = model.PhotoDescription, htmlAttributes: new class = control-label col-md-2 ) div class=
32、col-md-10 Html.EditorFor(model = model.PhotoDescription, new htmlAttributes = new class = form-control ) Html.ValidationMessageFor(model = model.PhotoDescription, , new class = text-danger ) /div /div div class=form-group label class=control-label col-md-2选择照片:/label div class=col-md-10 input type=f
33、ile name=file id=file style=width: 100%; data-val=true data-val-required=请选择图像 / Html.ValidationMessage(file, new class = text-danger ) /div /div div class=form-group div class=col-md-offset-2 col-md-10 input type=submit value=Create class=btn btn-default / /div /div /div input type=hidden name=albumName id=albumName value=ViewBag.AlbumTitle / input type=hidde
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 小学生讲课课件图片
- 车辆抵押权登记与抵押物抵押协议
- 诚信通平台企业信用评级与风险管理合作协议
- 餐饮店租赁权及商标使用权转让合同范本
- 场监督管理局违反合同法行政处罚协议
- 铁路线路相关知识考试试卷含答案真题
- 健身器材安全标准与老年人适应性设计考核试卷
- 低温仓储仓库空气质量监测与管理考核试卷
- 水产养殖市场消费者购买决策影响因素分析考核试卷
- 家电行业社交媒体营销数据挖掘与分析考核试卷
- 信息安全培训《钓鱼邮件防范技巧》
- 2025至2030中国烫印箔行业发展趋势分析与未来投资战略咨询研究报告
- 部编版高一语文必修上册教案计划
- 临时工请假管理制度
- 小学用电安全课件
- 2025年北京市高考英语试卷真题(含答案解析)
- 2025年中国浮萍项目投资可行性研究报告
- 商洛学院《大学学术综合英语》2023-2024学年第二学期期末试卷
- 2025年高考英语全国二卷听力试题答案详解讲解(课件)
- 高级采气工理论练习卷附答案
- 国开电大【管理英语3单元自测1-8答案】+【管理英语4形考任务单元自测1-8答案】
评论
0/150
提交评论