About ASP.NET MVC route
-
06-07-2021 - |
Pergunta
Such as I get a filter model:
public class Filter
{
public int Id{get;set;}
public string Name{get;set;}
public DateTime CreateTime{get;set;}
}
And there is a SearchController action like:
public ActionResult Search(Filter filterModel)
{
List<Model> model =SampleBll.get(filterModel)
}
so the question is.How to configure URL like
/Search/{Filter.Id}_{Filter.Name}_{Filter.CreatTime}/
Thank you for your help
Solução
You can treat {Filter.Id}_{Filter.Name}_{Filter.CreatTime}
as string filter
and parse it in your controller.
public ActionResult Search(string filter)
{
var parts = filter.Split("|".ToCharArray());
Filter model = new Filter();
model.Id = Int32.Parse(parts[0]);
// ...
}
Outras dicas
You would first need to add the following route into your Global.asax.cs RegisterRoutes
method, before the default route:
routes.MapRoute(
"Search", // Name
"Search/{Id}_{Name}_{CreateTime}", // url format
new { controller = "Search", action = "Search" } // Defaults
);
Once this is done, going to your application using a url such as /Search/123_Test_06-01-2011
would trigger the route, and the built-in object mapping will take care of mapping the properties to the model as long as the parameter names in the route match the names of the property and they can be successfully cast to the corresponding type.
Use string or change _ per / {Filter.Id}/{Filter.Name}/{Filter.CreatTime}