




下载本文档
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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年煤炭综合采掘机械设备项目建议书
- 2025年生化分析仪器试剂合作协议书
- 2025-2030减肥中草药行业市场发展分析及投资前景研究报告
- 2025-2030内燃机车行业市场深度分析及发展策略研究报告
- 2025-2030养老行业市场发展分析及发展趋势前景预测报告
- 2025-2030全球及中国非阿片类镇痛药行业市场现状供需分析及投资评估规划分析研究报告
- 2025-2030全球及中国遮瑕笔行业市场现状供需分析及投资评估规划分析研究报告
- 2025-2030全球及中国网络流量分析软件行业市场现状供需分析及市场深度研究发展前景及规划可行性分析研究报告
- 建设工程质量保证体系审查表
- cmk 设备能力分析计数表格
- 化工有限公司职业卫生管理制度
- 2022年新改版教科版五年级下册科学全册实验记录单(实验必备)
- 2023年四级汽车美容装潢工资格考试题库(浓缩600题)
- 慢性肾衰竭教学查房
- ZZ031 园林微景观设计与制作赛项赛题-2023年全国职业院校技能大赛拟设赛项赛题完整版(10套)
- 吉林师范成人教育《大学英语2》期末考试复习题及参考答案
- 电力设计收费标准2018
- GB/T 17214.4-2005工业过程测量和控制装置的工作条件第4部分:腐蚀和侵蚀影响
- 显微镜检验报告
评论
0/150
提交评论