Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

c# - ASP.NET MVC controller actions with custom parameter conversion?

I want to set up a ASP.NET MVC route that looks like:

routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{idl}", // URL with parameters
  new { controller = "Home", action = "Index", idl = UrlParameter.Optional } // Parameter defaults
);

That routes requests that look like this...

Example/GetItems/1,2,3

...to my controller action:

public class ExampleController : Controller
{
    public ActionResult GetItems(List<int> id_list)
    {
        return View();
    }
}

The question is, what do I set up to transform the idl url parameter from a string into List<int> and call the appropriate controller action?

I have seen a related question here that used OnActionExecuting to preprocess a string, but did not change the type. I don't think that will work for me here, because when I override OnActionExecuting in my controller and inspect the ActionExecutingContext parameter, I see that the ActionParameters dictionary already has an idl key with a null value- presumably, an attempted cast from string to List<int>... this is the part of the routing I want to be in control of.

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A nice version is to implement your own Model Binder. You can find a sample here

I try to give you an idea:

public class MyListBinder : IModelBinder
{   
     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
     {   
        string integers = controllerContext.RouteData.Values["idl"] as string;
        string [] stringArray = integers.Split(',');
        var list = new List<int>();
        foreach (string s in stringArray)
        {
           list.Add(int.Parse(s));
        }
        return list;  
     }  
}


public ActionResult GetItems([ModelBinder(typeof(MyListBinder))]List<int> id_list) 
{ 
    return View(); 
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...