Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 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 Answer

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(); 
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...