Skip to content

Commit 1a298c4

Browse files
committed
Added ViewModel and updated the edit screen
1 parent 6752603 commit 1a298c4

File tree

18 files changed

+1222
-148
lines changed

18 files changed

+1222
-148
lines changed

BookCollection/BookCollection.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@
215215
<Compile Include="Helpers\CustomHtmlHelper.cs" />
216216
<Compile Include="Helpers\CustomWebViewPage.cs" />
217217
<Compile Include="Helpers\DownloadExcelFileActionResult.cs" />
218+
<Compile Include="Helpers\HtmlGrid.cs" />
218219
<Compile Include="Helpers\ImageResult.cs" />
219220
<Compile Include="Helpers\ImageUpload.cs" />
220221
<Compile Include="Helpers\Validators.cs" />
@@ -227,6 +228,7 @@
227228
<Compile Include="Models\Publisher.cs" />
228229
<Compile Include="Models\Subject.cs" />
229230
<Compile Include="Properties\AssemblyInfo.cs" />
231+
<Compile Include="ViewModels\BookViewModel.cs" />
230232
<Compile Include="ViewModels\CategoryGroup.cs" />
231233
<Compile Include="ViewModels\Statistics.cs" />
232234
</ItemGroup>

BookCollection/Controllers/AuthorsController.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,8 @@ public ActionResult Details(int? id)
6868
}
6969
else
7070
{
71-
author.Books = db.Query<Book>().Where(b => b.AuthorID == author.AuthorID).ToList();
71+
72+
author.Books = db.Query<Book>().Where(b => b.Authors.Any(a => a.AuthorID == author.AuthorID)).ToList();
7273
}
7374
return View(author);
7475
}

BookCollection/Controllers/BooksController.cs

Lines changed: 97 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@
1010
using BookCollection.Models;
1111
using PagedList;
1212
using BookCollection.Helpers;
13+
using BookCollection.ViewModels;
1314

1415
namespace BookCollection.Controllers
1516
{
1617
public class BooksController : Controller
1718
{
1819
private readonly IBookContext _db;
1920

20-
//TODO use base controller
2121
public BooksController(IBookContext dbContext)
2222
{
2323
_db = dbContext;
@@ -34,7 +34,7 @@ public ActionResult Index(string sortOrder, string currentFilter, string bookCat
3434
ViewBag.YearSortParm = String.IsNullOrEmpty(sortOrder) ? "year_desc" : "year";
3535
ViewBag.CategorySortParm = String.IsNullOrEmpty(sortOrder) ? "category_desc" : "category";
3636
ViewBag.SerieSortParm = String.IsNullOrEmpty(sortOrder) ? "serie_desc" : "serie";
37-
*/
37+
3838
if (!String.IsNullOrEmpty(sortOrder) && sortOrder.Contains("_"))
3939
{
4040
string[] sort = sortOrder.ToLowerInvariant().Split(new [] { '_' });
@@ -47,21 +47,13 @@ public ActionResult Index(string sortOrder, string currentFilter, string bookCat
4747
{
4848
ViewBag.AuthorSortParm = sort[1].Equals("desc") ? "author_desc" : "author_asc";
4949
}
50-
/*
51-
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "name_asc";
52-
ViewBag.AuthorSortParm = String.IsNullOrEmpty(sortOrder) ? "author_desc" : "author";
53-
ViewBag.PublisherSortParm = String.IsNullOrEmpty(sortOrder) ? "publisher_desc" : "publisher";
54-
ViewBag.YearSortParm = String.IsNullOrEmpty(sortOrder) ? "year_desc" : "year";
55-
ViewBag.CategorySortParm = String.IsNullOrEmpty(sortOrder) ? "category_desc" : "category";
56-
ViewBag.SerieSortParm = String.IsNullOrEmpty(sortOrder) ? "serie_desc" : "serie";
57-
*/
58-
5950
}
6051
else
6152
{
6253
// default sort on name
6354
sortOrder = "name_asc";
6455
}
56+
*/
6557

6658
if (searchString != null)
6759
{
@@ -101,12 +93,12 @@ public ActionResult Index(string sortOrder, string currentFilter, string bookCat
10193
case "publisher_desc":
10294
books = books.OrderByDescending(s => s.Publisher.Name);
10395
break;
104-
case "author_asc":
96+
/*case "author_asc":
10597
books = books.OrderBy(s => s.MainAuthor);
10698
break;
10799
case "author_desc":
108100
books = books.OrderByDescending(s => s.MainAuthor);
109-
break;
101+
break;*/
110102
case "category_asc":
111103
books = books.OrderBy(s => s.Category.Title);
112104
break;
@@ -182,20 +174,22 @@ public ActionResult Details(int? id)
182174
// GET: Books/Create
183175
public ActionResult Create()
184176
{
185-
PopulateAuthorDropDownList();
177+
// One to many relationships
186178
PopulateCategoryDropDownList();
187179
PopulatePublishersDropDownList();
188-
PopulateMainSubjectDropDownList();
189-
PopulateSubjectDropDownList();
190-
return View();
180+
181+
// Create model with defaults
182+
var bookViewModel = new Book();
183+
184+
return View(bookViewModel);
191185
}
192186

193187
// POST: Books/Create
194188
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
195189
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
196190
[HttpPost]
197191
[ValidateAntiForgeryToken]
198-
public ActionResult Create([Bind(Include = "BookID,Title,AlternativeTitle,AuthorID,CategoryID,InitialPrintedYear,ActualPrintYear,Language,Material,Read,Pages,ISBN,Website,CoverLink,Rating,CodeWithinSerie,Condition,ReviewNote,Location")] Book book)
192+
public ActionResult Create([Bind(Include = "BookID,Title,AlternativeTitle,AuthorID,CategoryID,PublisherID,InitialPrintedYear,ActualPrintYear,Language,Material,Read,Pages,ISBN,Website,CoverLink,Rating,CodeWithinSerie,Condition,ReviewNote,Location")] Book book)
199193
{
200194
if (ModelState.IsValid)
201195
{
@@ -204,28 +198,15 @@ public ActionResult Create([Bind(Include = "BookID,Title,AlternativeTitle,Author
204198
_db.SaveChanges();
205199
return RedirectToAction("Index");
206200
}
207-
PopulateAuthorDropDownList(book.AuthorID);
201+
208202
PopulateCategoryDropDownList(book.CategoryID);
209203
PopulatePublishersDropDownList(book.PublisherID);
210-
PopulateMainSubjectDropDownList(book.MainSubjectID);
211204

212-
if (book.Subjects.Count > 0)
213-
{
214-
PopulateSubjectDropDownList(book.Subjects.First().SubjectID);
215-
}else
216-
{
217-
PopulateSubjectDropDownList();
218-
}
219205

220206
return View(book);
221207
}
222208

223209
#region dropdowns
224-
private void PopulateAuthorDropDownList(object selected = null)
225-
{
226-
var query = _db.Query<Author>().OrderBy(a => a.Lastname);
227-
ViewBag.AuthorID = new SelectList(query, "AuthorID", "Fullname", selected);
228-
}
229210
private void PopulateCategoryDropDownList(object selected = null)
230211
{
231212
var query = _db.Query<Category>().OrderBy(a => a.Title);
@@ -237,18 +218,6 @@ private void PopulatePublishersDropDownList(object selected = null)
237218
var query = _db.Query<Publisher>().OrderBy(a => a.Name);
238219
ViewBag.PublisherID = new SelectList(query, "PublisherID", "Name", selected);
239220
}
240-
241-
private void PopulateMainSubjectDropDownList(object selected = null)
242-
{
243-
var query = _db.Query<Subject>().OrderBy(a => a.Name);
244-
ViewBag.MainSubjectID = new SelectList(query, "MainSubjectID", "Name", selected);
245-
}
246-
247-
private void PopulateSubjectDropDownList(object selected = null)
248-
{
249-
var query = _db.Query<Subject>().OrderBy(a => a.Name);
250-
ViewBag.SubjectID = new SelectList(query, "SubjectID", "Name", selected);
251-
}
252221
#endregion
253222

254223

@@ -259,34 +228,108 @@ public ActionResult Edit(int? id)
259228
{
260229
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
261230
}
262-
Book book = _db.Query<Book>().FirstOrDefault(b => b.BookID == id);
231+
Book book = _db.Query<Book>()
232+
.Include(i => i.Authors)
233+
.Include(i => i.Subjects)
234+
.First(b => b.BookID == id);
235+
263236
if (book == null)
264237
{
265238
return HttpNotFound();
266239
}
267-
PopulateAuthorDropDownList(book.AuthorID);
240+
268241
PopulateCategoryDropDownList(book.CategoryID);
269242
PopulatePublishersDropDownList(book.PublisherID);
270-
return View(book);
243+
244+
var allAuthors = _db.Query<Author>().Select(o => new SelectListItem
245+
{
246+
Text = o.Lastname,
247+
Value = o.AuthorID.ToString()
248+
});
249+
250+
var allSubjects = _db.Query<Subject>().Select(o => new SelectListItem
251+
{
252+
Text = o.Name,
253+
Value = o.SubjectID.ToString()
254+
});
255+
256+
257+
var bookViewModel = new BookViewModel()
258+
{
259+
Book = book,
260+
AllAuthors = allAuthors,
261+
AllSubjects = allSubjects
262+
};
263+
264+
var tets = bookViewModel.SelectedSubjects;
265+
var tets2 = bookViewModel.SelectedAuthors;
266+
267+
return View(bookViewModel);
271268
}
272269

273270
// POST: Books/Edit/5
274271
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
275272
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
276273
[HttpPost]
277274
[ValidateAntiForgeryToken]
278-
public ActionResult Edit([Bind(Include = "BookID,Title,AlternativeTitle,CreationDate,InitialPrintedYear,ActualPrintYear,Language,Material,Read,Pages,ISBN,Website,CoverLink,Rating,CodeWithinSerie,Condition,ReviewNote,Location")] Book book)
275+
//public ActionResult Edit([Bind(Include = "BookID,AuthorID,MainAuthorID,MainSubjectID,SubjectID,Title,AlternativeTitle,PublisherID,CreationDate,InitialPrintedYear,ActualPrintYear,CategoryID,Language,Material,Read,Pages,ISBN,Website,CoverLink,Rating,CodeWithinSerie,Condition,ReviewNote,Location,Serie")] Book book)
276+
public ActionResult Edit(BookViewModel bookViewModel)
279277
{
278+
279+
280280
if (ModelState.IsValid)
281281
{
282-
_db.Update(book);
283-
_db.SaveChanges();
282+
283+
var bookToUpdate = _db.Query<Book>()
284+
.Include(i => i.Authors)
285+
.Include(i => i.Subjects).First(i => i.BookID == bookViewModel.Book.BookID);
286+
287+
if (TryUpdateModel(bookToUpdate, "Book"))
288+
{
289+
// Update references to author (Add new/Remove old)
290+
var newAuthors = _db.Query<Author>().Where(
291+
m => bookViewModel.SelectedAuthors.Contains(m.AuthorID)).ToList();
292+
var updatedAuthors = new HashSet<int>(bookViewModel.SelectedAuthors);
293+
foreach (Author author in _db.Query<Author>())
294+
{
295+
if (!updatedAuthors.Contains(author.AuthorID))
296+
{
297+
bookToUpdate.Authors.Remove(author);
298+
}
299+
else
300+
{
301+
bookToUpdate.Authors.Add(author);
302+
}
303+
}
304+
305+
// Update references to subjects (Add new/Remove old)
306+
var newSubjects = _db.Query<Subject>().Where(
307+
s => bookViewModel.SelectedSubjects.Contains(s.SubjectID)).ToList();
308+
var updatedSubjects = new HashSet<int>(bookViewModel.SelectedSubjects);
309+
310+
foreach (Subject sub in _db.Query<Subject>())
311+
{
312+
if (!updatedSubjects.Contains(sub.SubjectID))
313+
{
314+
bookToUpdate.Subjects.Remove(sub);
315+
}
316+
else
317+
{
318+
bookToUpdate.Subjects.Add(sub);
319+
}
320+
}
321+
322+
_db.SetState(bookToUpdate, EntityState.Modified);
323+
_db.SaveChanges();
324+
}
325+
284326
return RedirectToAction("Index");
285327
}
286-
PopulateAuthorDropDownList(book.AuthorID);
287-
PopulateCategoryDropDownList(book.CategoryID);
288-
PopulatePublishersDropDownList(book.PublisherID);
289-
return View(book);
328+
329+
PopulateCategoryDropDownList(bookViewModel.Book.CategoryID);
330+
PopulatePublishersDropDownList(bookViewModel.Book.PublisherID);
331+
332+
return View(bookViewModel);
290333
}
291334

292335
// GET: Books/Delete/5

BookCollection/Controllers/SubjectsController.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public ActionResult Details(int? id)
6767
return HttpNotFound();
6868
}else
6969
{
70-
subject.Books = db.Query<Book>().Where(b => b.MainSubjectID == subject.SubjectID).ToList();
70+
subject.Books = db.Query<Book>().Where(b => b.Subjects.Any(s => s.SubjectID == subject.SubjectID)).ToList();
7171
}
7272
return View(subject);
7373
}

BookCollection/DAL/BookContext.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,15 @@ protected override void OnModelCreating(DbModelBuilder modelBuilder)
5151
//Many to Many relationships: intermediate table BookAuthors
5252
modelBuilder.Entity<Book>()
5353
.HasMany(b => b.Authors).WithMany(a => a.Books)
54-
.Map(t => t.MapLeftKey("BookID")
55-
.MapRightKey("AuthorID")
54+
.Map(t => t.MapLeftKey("BookRefID")
55+
.MapRightKey("AuthorRefID")
5656
.ToTable("BookAuthors"));
5757

5858
//Many to Many relationships: intermediate table BookSubjects
5959
modelBuilder.Entity<Book>()
6060
.HasMany(b => b.Subjects).WithMany(s => s.Books)
61-
.Map(t => t.MapLeftKey("BookID")
62-
.MapRightKey("SubjectID")
61+
.Map(t => t.MapLeftKey("BookRefID")
62+
.MapRightKey("SubjectRefID")
6363
.ToTable("BookSubjects"));
6464

6565
}

BookCollection/DAL/SeedData/BookInitializer.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -156,22 +156,23 @@ public IEnumerable<Book> GetBooks(IEnumerable<Publisher> pubs, IEnumerable<Autho
156156
{
157157
pub = pubs.FirstOrDefault(a => a.Name.Equals("?", StringComparison.OrdinalIgnoreCase));
158158
}
159-
Subject mainSub = null;
160-
List<Subject> otherSub = new List<Subject>();
159+
//Subject mainSub = null;
160+
List<Subject> subjects = new List<Subject>();
161+
161162
if (!string.IsNullOrWhiteSpace(item.Subjects1))
162163
{
163164
var splt = item.Subjects1.Split(splitters, StringSplitOptions.RemoveEmptyEntries);
164-
mainSub = subs.FirstOrDefault(s => s.Name.Equals(splt[0], StringComparison.OrdinalIgnoreCase));
165+
//mainSub = subs.FirstOrDefault(s => s.Name.Equals(splt[0], StringComparison.OrdinalIgnoreCase));
165166

166-
if (splt.Length > 1)
167+
if (splt.Length > 0)
167168
{
168-
for (int i=1; i < splt.Length; i++)
169+
for (int i=0; i < splt.Length; i++)
169170
{
170171
string subTitle = splt[i].Trim();
171172
if (!IsBlacklistedSubject(subTitle)) {
172173
var dbSup = subs.FirstOrDefault(s => s.Name.Equals(subTitle, StringComparison.OrdinalIgnoreCase));
173-
if (dbSup != null && !otherSub.Contains(dbSup)) {
174-
otherSub.Add(dbSup);
174+
if (dbSup != null && !subjects.Contains(dbSup)) {
175+
subjects.Add(dbSup);
175176
}
176177
}
177178
}
@@ -192,8 +193,7 @@ public IEnumerable<Book> GetBooks(IEnumerable<Publisher> pubs, IEnumerable<Autho
192193
Serie = Converters.RemoveSerieNr(item.Serie),
193194
CreationDate = nullDate,
194195
Publisher = pub,
195-
MainSubject = mainSub,
196-
Subjects = otherSub,
196+
Subjects = subjects,
197197
Code = item.Contents,
198198
Condition = Condition.Used,
199199
CodeWithinSerie = Converters.ExtractSerieNr(item.Serie),

0 commit comments

Comments
 (0)