vgquotes/Src/VideoGameQuotes.Web/Models/BrowseModelBinder.cs

80 lines
2.1 KiB
C#

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Portoa.Web.Util;
namespace VideoGameQuotes.Web.Models {
public class BrowseModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var model = new BrowseModel {
SortMethod = SortMethod.Alphabetical,
SortOrder = SortOrder.Ascending
};
var qualifierText = (controllerContext.RouteData.Values["qualifiers"] ?? string.Empty).ToString();
if (string.IsNullOrEmpty(qualifierText)) {
return model;
}
var segments = qualifierText.Split('/').ToArray();
for (var i = 0; i < segments.Length; i++) {
switch (segments[i]) {
case "game":
case "system":
case "category":
case "publisher":
if (i < segments.Length - 1) {
var ids = ParseCommaSeparatedIntegers(segments[i + 1]).ToArray(); //nhibernate requires non-iterator
switch (segments[i]) {
case "game":
model.GameIds = ids;
break;
case "system":
model.SystemIds = ids;
break;
case "category":
model.CategoryIds = ids;
break;
case "publisher":
model.PublisherIds = ids;
break;
}
i++; //loop unroll ftw
}
break;
case "alphabetical":
model.SortMethod = SortMethod.Alphabetical;
break;
case "date":
model.SortMethod = SortMethod.Date;
break;
case "rating":
model.SortMethod = SortMethod.Rating;
break;
case "asc":
model.SortOrder = SortOrder.Ascending;
break;
case "desc":
model.SortOrder = SortOrder.Descending;
break;
default:
controllerContext.AddModelError("qualifiers", "Unknown qualifier: " + segments[i]);
break;
}
}
return model;
}
private static IEnumerable<int> ParseCommaSeparatedIntegers(string value) {
foreach (var id in value.Split(',')) {
int result;
if (int.TryParse(id, out result)) {
yield return result;
}
}
}
}
}