使用破折号( - )在ASP.MVC参数 [英] Using a dash (-) in ASP.MVC parameters

查看:131
本文介绍了使用破折号( - )在ASP.MVC参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<% using (Html.BeginForm("SubmitUserName")) { %>
    <input type='text' name='user-name' />
    <input type='submit' value='Send' />
<% } %>

应该是什么相应的动作方法的签名接受用户名参数?

public ActionResult SubmitUserName(string user-name) {...}

方法签名上面并没有出于某种原因; - )

Method signature above does not work for some reason ;-)

我知道有一个 ActionNameAttribute 来处理与操作名称短划线的情况。有什么样 ParameterNameAttribute

I know there is an ActionNameAttribute to handle situation with a dash in action name. Is there something like ParameterNameAttribute?

推荐答案

因为每个人都有所指出的,最简单的解决方法是不再使用破折号。如果你真的需要短跑,你可以创建自己的ActionFilterAttribute来处理它,但。

As everyone has noted, the easiest fix would be not to use a dash. If you truly need the dash, you can create your own ActionFilterAttribute to handle it, though.

是这样的:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class ParameterNameAttribute :  ActionFilterAttribute
{
    public string ViewParameterName { get; set; }
    public string ActionParameterName { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.ActionParameters.ContainsKey(ViewParameterName))
        {
            var parameterValue = filterContext.ActionParameters[ViewParameterName];
            filterContext.ActionParameters.Add(ActionParameterName, parameterValue);   
        }
    }
}

然后,您可以将过滤器应用于适当的行动方式:

You would then apply the filter to the appropriate Action method:

[ParameterName( ViewParameterName = "user-data", ActionParameterName = "userData")]
[ParameterName( ViewParameterName = "my-data", ActionParameterName = "myData" )]
    public ActionResult About(string userData, string myData)
    {
        return View();
    }

您可能会想增强ParameterNameAttribute处理/小写,但是这将是基本思想。

You would probably want to enhance the ParameterNameAttribute to handle upper/lower case, but that would be the basic idea.

这篇关于使用破折号( - )在ASP.MVC参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆