這可能嗎?有任何想法嗎?
我會繼續查詢字符串參數進行過濾。
但是,如果你想實現你已經在你的問題問的URL我將介紹兩種可能的技術。
爲此,我將在這裏介紹兩種方法我假設你已經有一個視圖模型:
public class FilterViewModel
{
public string Key { get; set; }
public string Value { get; set; }
}
和控制器:
public class RealtyController : Controller
{
public ActionResult Filter(IEnumerable<FilterViewModel> filters)
{
... do the filtering ...
}
}
第一個選項是寫
public class FilterViewModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var filtersValue = bindingContext.ValueProvider.GetValue("pathInfo");
if (filtersValue == null || string.IsNullOrEmpty(filtersValue.AttemptedValue))
{
return Enumerable.Empty<FilterViewModel>();
}
var filters = filtersValue.AttemptedValue;
var tokens = filters.Split('/');
if (tokens.Length % 2 != 0)
{
throw new Exception("Invalid filter format");
}
var result = new List<FilterViewModel>();
for (int i = 0; i < tokens.Length - 1; i += 2)
{
var key = tokens[i];
var value = tokens[i + 1];
result.Add(new FilterViewModel
{
Key = tokens[i],
Value = tokens[i + 1]
});
}
return result;
}
}
:將與
IEnumerable<FilterViewModel>
類型相關聯的自定義模型綁定
將在Application_Start
註冊:
ModelBinders.Binders.Add(typeof(IEnumerable<FilterViewModel>), new FilterViewModelBinder());
,你也將有一個過濾路由器:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Filter",
"realty/filter/{*pathInfo}",
new { controller = "Realty", action = "Filter" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
第二種可能性是寫一個自定義路由
public class FilterRoute : Route
{
public FilterRoute()
: base(
"realty/filter/{*pathInfo}",
new RouteValueDictionary(new
{
controller = "realty", action = "filter"
}),
new MvcRouteHandler()
)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var rd = base.GetRouteData(httpContext);
if (rd == null)
{
return null;
}
var filters = rd.Values["pathInfo"] as string;
if (string.IsNullOrEmpty(filters))
{
return rd;
}
var tokens = filters.Split('/');
if (tokens.Length % 2 != 0)
{
throw new Exception("Invalid filter format");
}
var index = 0;
for (int i = 0; i < tokens.Length - 1; i += 2)
{
var key = tokens[i];
var value = tokens[i + 1];
rd.Values[string.Format("filters[{0}].key", index)] = key;
rd.Values[string.Format("filters[{0}].value", index)] = value;
index++;
}
return rd;
}
}
這將在您的012登記方法:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("Filter", new FilterRoute());
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
哇!神奇的我的朋友......永遠出色的答案。我認爲現在我會繼續使用QueryString方法,因爲它使用我在問題中提到的QueryString操作按預期工作。我相信你的答案將來會用到。對我們簡單的凡人來說很有參考價值 – 2012-02-26 15:29:15