user2541688
user2541688

Reputation:

Forcing HTTP GET query parameters in ASP.NET MVC 5 to be all lowercase when their viewmodel property member names are captialised

Not really sure of whether this is possible but here goes...

In my project I have some ViewModels, all their property member names are capitalised, I create a form using FormMethod.HttpGet and HtmlHelpers such as EditorFor(), the helper uses the member properties name as the form elements name (e.g. <input type="text" name="Address" />) when the form is submitted and i catch the viewmodel (ActionResult method(ViewModel model)) in the action methods. I'm using FormMethod.HttpGet and because of this routing isn't available without JavaScript, so the form elements get parsed as query parameters in the URL.

Because all the viewmodels are capitalised, all the form parameters are also capitalised, and i have a distinct feeling that this may cause problems somewhere down the road in the future, whether it's JsonResult formatting or SEO, or something else i don't know, but i would rather they be be lowercase, but here's the kicker, i don't whether i can do this while keeping the capitalisation on the ViewModel member properties.

Upvotes: 1

Views: 1825

Answers (1)

devfric
devfric

Reputation: 7542

You could use lowercase URLs which is an optional configuration setting in ASP.NET MVC

In ASP.NET 4:

{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.LowercaseUrls = true;

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

In ASP.NET 5:

public void ConfigureServices(IServiceCollection services)
{
// ...
    services.ConfigureRouting(routeOptions =>
    {
        routeOptions.AppendTrailingSlash = true
        routeOptions.LowercaseUrls = true;
    });
}
}

For HttpGet

  • you could use javascript to lowercase the url or the parameters passed after you constructed it using toLowerCase() method

  • Or as CodeCaster mentioned create an HTMLHelper to use in your cshtml e.g

    @Html.LowerTextBoxFor(x=>x.Property1)
    

If you want to lowercase for SEO. You could alternatively use a web server extension to lowercase urls e.g. IIS Url Rewrite Extension

With regards to JSON capitalization. There are configuration options for this as well e.g. in ASP.NET 5 to convert from C# PascalCase to camelCase which JSON uses.

services.AddMvc()
.AddJsonOptions(options =>
{
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Ignore;
    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

}); 

Upvotes: 1

Related Questions