Showing posts with label .NET Core. Show all posts
Showing posts with label .NET Core. Show all posts

How to add\pre-fill https://www. to input fields with type URL?

This is quick post for something I had to implement today. It's related to input fields with type="url".

What did I do?

Opened Visual Studio Code on the Views folder of a large ASP.NET MVC project and then searched for asp-for=(.*)URL using Regular Expression. That linked me to all the places (Razor .cshtml views) which had a @model (Model\ViewModel) class which happens to have an URL property.

Some of those Model\ViewModel properties didn't have the [Url] data annotation. I proceeded to add it to properties where it was missing. This data annotation is responsible for correctly generating the <input type="url" ... > on the HTML when using Razor's html helpers like this for example:

<input asp-for="Organization.URL" class="form-control">
It'll generate this HTML code:

<input class="form-control"
type="url"
data-val="true"
data-val-url="The URL field is not a valid fully-qualified http, https, or ftp URL."
id="Organization_URL"
name="Organization.URL"
value="">
With that in place I crafted some jQuery\JavaScript code that does the magic:

/**
* For all inputs with type URL and which are empty,
* we add https://www. when the input has focus.
*/
function addHttpsWwwToInputTypeUrl() {
$("input[type='url'][value='']").focus(function () {
$(this).val('https://www.')
});
}
The code is self-explanatory. It selects all inputs with type="url" and which are empty. Once the input gets focus, https://www. is added automatically to the input's value. The user now only has to complete the URL address. No more typing https://www. everytime.

The only thing necessary now is to call this JavaScript function in a central place so that it can be applied everywhere in your project.

That's it... a simple but nice user experience to have in your app. Hope it helps.

Using IOptions from .NET Core in .NET Framework 4.5.1+ - Ninject dependency injection version

This post is based on this awesome article I found @ Medium:

Configuration Management in Legacy .NET Applications (.NET Framework 4.5.1+)

I wanted to use the cool IOptions interface to grab some configs from appsettings.json. The sad thing is that it's intended to be used with .NET Core but the article mentioned above tells us that we can circumvent that with some extension code.

I won't be able to use it anymore because I just found out that I can't in the current project setup I'm working on.

As I had already converted the AutoFac code to Ninject, I'm just sharing it here in case it's useful...

You'll need to test it.

Note: make sure you have installed the following NuGet packages:

- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Options
- Microsoft.Extensions.Options.ConfigurationExtensions