Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dash (-) in ASP.MVC parameters

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

What should be a signature of a corresponding Action method to accept user-name parameter?

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

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

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

like image 851
THX-1138 Avatar asked Aug 11 '10 17:08

THX-1138


3 Answers

Not answering the actual question based on the technlogy in question, but anyway, the world moves forward in some areas; in AspNetCore.Mvc you can simply do:

    [HttpGet()]
    public ActionResult SubmitUserName( [FromHeader(Name = "user-Name")] string userName) {...}
like image 123
Caad9Rider Avatar answered Sep 21 '22 15:09

Caad9Rider


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.

Something like:

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

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

like image 13
Andy Wilson Avatar answered Sep 21 '22 09:09

Andy Wilson


Create a pseudo-parameter in the first line of the action method:

public ActionResult SubmitUserName()
{
    string userName = Request.Params["user-name"];
    ...
}
like image 13
Edward Brey Avatar answered Sep 22 '22 09:09

Edward Brey