ASP.NET Mvc - nullable parameters and comma as separator

别来无恙 提交于 2019-12-06 12:48:52

As far as I know .Net routing doesn't let you do multiple nullable parameters like that. Multiple parameters will only work if they are missing working backwards from the end and with the separator also missing so you'd get matches on

user/find,bob,2,live
user/find,bob,2
user/find,bob
user/find

It'd be a lot easier to use querystrings for what you're trying to do.

Edit based on comment:

If this is necessary then you could try doing it this way (though it's not a nice approach)

Change your path to match

{Controller}/{Action},{*parameters}

Make sure to put a constraint on the action and controller so this is limited to as few as possible.

Rename each action that would take your full list to something else, adding a standard prefix to each one would be the cleanest way, and add the [NonAction] attribute. Add a new method with the original name that takes a string, this string is a comma separated string of your variables. In this method split the string and return the original action passing in the values from the split.

So you go from:

public ActionResult Find(string name, int page, string status){
    //Do stuff here
    return View(result);
}

To

public ActionResult Find(string parameters){
    string name;
    int? page;
    string status;
    //split parameters and parse into variables
    return FindAction(name, page, status);
}

[NonAction]
public ActionResult FindAction(string parameters){
    //Do what you did in your previous Find action
    return View(results);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!