Handling MVC2 variables with hyphens in their name

三世轮回 提交于 2019-12-05 08:07:01

Have you tried [Bind(Prefix="First-name")]? It might work...

One way would be with a custom model binder. Another way would be with an action filter. Use the model binder if you want to do this on a specific type. Use the action filter if you want to do this on a specific action or controller. So for the latter method you could do something like:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var keys = filterContext.HttpContext.Request.QueryString.AllKeys.Where(k => k.Contains('-'));
        foreach(var k in keys)
        {
            filterContext.ActionParameters.Add(
                new KeyValuePair<string, object>(
                    k.Replace('-', '_'), filterContext.HttpContext.Request.QueryString[k]));
        }
        base.OnActionExecuting(filterContext);
    }

I had the same problem. In the end rather than doing something too complex I just get the query string parameters using

string First_Name = Request["First-Name"];

You may want to check for NUlls incase the parameter is not there, but this sorted it out for me. You can also include an optional parameter for the ActionResult for test purposes etc..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!