asp.net MVC4 use MongoDB to create album management instance sharing
TIPS: 1.Image to Base64 save to MongoDB field
2. The data model is a nested association
First define the model layer:
public class Photo:iequatable<photo> {[Required] public string Photoname {get; set;}
[Required] public string photodescription {get; set;}
public string Serverpath {get; set;}
Public Photo () {} public Photo (string name, String desc) {photoname = name;
Photodescription = desc; public bool Equals (Photo) {return string. Equals (Photoname, other.
Photoname);
} public interface Ialbumiterable {bool Hasnext ();
Photo current ();
Photo Next ();
Public 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 collection[count++];
else throw new IndexOutOfRangeException (); 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] public 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
Ilist<photo> Pictures {get; set;} Public Album () {Pictures = new list<photo> (); Titlephoto = new Photo ();
Public Album (string name, string owner, Photo pic) {name = name;
Owner = owner;
Titlephoto = pic;
Pictures = new list<photo> ();
Titlephoto = new Photo (); public bool InsertPicture (Photo pic) {if (! Pictures.contains (pic)) {Pictures.Add (pic);
return true;
else throw new ArgumentException (); public bool Insertpictures (list<photo> 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 int Count {get {pictures.count;}
Public Photo This[int Index] {get {return pictures[index];}
set {Pictures[index] = value;}
Public ialbumiterable Getiterator () {Return to New albumiterator (this);
}
}
The MongoAlbumPerformer.cs and ServerPathFinder.cs code for the
services layer are as follows:
public class Mongoalbumperformer {protected static imongoclient client;
protected static Imongodatabase database;
private static imongocollection<album> collection;
private string CollectionName; Public Mongoalbumperformer (String databaseName, String collectionname) {client = new Mongoclient (Configurationma Nager. connectionstrings["MongoDB"].
ConnectionString); Database = client.
Getdatabase (DatabaseName);
This.collectionname = CollectionName; Collection = database.
Getcollection<album> (CollectionName, new mongocollectionsettings {Assignidoninsert = true});
} public void Setcollection (string collectionname) {this.collectionname = CollectionName; Collection = database.
Getcollection<album> (CollectionName); The 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.
Insertone (document); Public list<album> Getalbumsbyusername (string username) {var projection = Builders<album>. 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). Project<album> (projection).
ToList ();
return result; Public Album Getpicturesbyalbumname (string albumname) {var projection = Builders<album>. Projection.
Include (a => a.pictures); var result = collection. Find (a => A.owner = = HttpContext.Current.User.Identity.Name & a.name = = Albumname). Project<album> (projection).
FirstOrDefault ();
return result; } public void Updatealbumaddphoto (string albumname, Photo Photo) {var builder = Builders<album>.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 ();
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 = Builders<album>.
Update.push (a => a.pictures, picture); Collection.
Updateone (filter, update, new UpdateOptions {isupsert=true}); } public void Deletephotofromalbum (string albumname, String photoname) {var builder = Builders<album>.f
Ilter; var filter = Builder. Eq (f => f.name, Albumname) & Builder.
Eq (f => f.owner, HttpContext.Current.User.Identity.Name); var result = collection. Find (Filter).
Singleordefault (); if (result = = null) throwNew ArgumentException ("No Album of supplied name: {0}", albumname); else {var update = Builders<album>. Update. Pullfilter (a => a.pictures, Builders<photo>
Filter.eq (P => p.photoname, photoname)); Long Count = collection. Updateone (filter, update).
Matchedcount; }}public class Serverpathfinder {public string getbase64imagestring (HttpPostedFileBase file) {string mime = Regex.match (file. ContentType, @ "(? <=image/) \w+").
Value; byte[] bytes = new Byte[file.
ContentLength]; File. Inputstream.read (bytes, 0, file.
ContentLength); return string.
Format ("Data:image/{0};base64,{1}", mime, convert.tobase64string (bytes));
}
}
The
AlbumController.cs code is as follows:
public class Albumcontroller:controller {Mongoalbumperformer Mongod = new Mongoalbumperformer ("Test", "albums"); [HttpPost] public actionresult Albumpreview (Photo model, httppostedfilebase file, string albumname, string delete, str ing phot {if (delete = = "false") {if (file!= null) {if (!file). Contenttype.startswith ("image") {modelstate.addmodelerror ("file"), "select the correct format photo!"
");
else {Serverpathfinder finder = new Serverpathfinder (); Model. Serverpath = Finder.
getbase64imagestring (file); } if (Modelstate.isvalid) {Mongod.
Updatealbumaddphoto (albumname, model);
Modelstate.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 album = 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"), "select the correct format photo!"
");
else {Serverpathfinder 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;
return View (); Public ActionResult Create () {var albums = Mongod.
Getalbumsbyusername (HttpContext.User.Identity.Name);
Viewbag.albums = albums;
return View ();
}
}
Partial View view:
create.cshtml
@{viewbag.title = "Create";}
Run project results as shown in figure:
Homepage Create album:
Examples of pictures under the "Car" album, you can add pictures, delete pictures
Examples of pictures under QQ album
MongoDB data Storage Structure chart:
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.