Search code examples
javascriptjsonmacosasp.net-core-mvcunobtrusive-javascript

Visual Studio Mac appsettings.json allow unobtrusive javascript


@Ajax is not being recognized in razor views for my MVC application. I believe the reason is bc Unobtrusive Javascript isn't allowed for the newest version of VS Mac?

To fix this problem "the web" advises adding below to the web.config of the project.

enable unobtrusive JS screenshot

However .Net Core doesn't have that, now has appsettings.json, which looks like this:

appsettings.json screenshot

Anyone know how to allow unobtrusive-Javascript in JSON?


Solution

  • In Asp.Net core, When you use the input tag helpers to generate the input fields, it does generate the html 5 attributes on those inputs used by jQuery validate & unobtrusive validate plugin, based on the data annotations you have on your view model properties. As long as you include the needed 2 javascript files in your page, the client side validation will work. You do not need any web config setting or anything like that.

    Just include these 2 files to your page/layout

    <script src="~/js/jquery.validate.min.js"></script>
    <script src="~/js/jquery.validate.unobtrusive.min.js"></script>
    

    Assuming the 2 files exist in the js directory in the static content root (wwwroot directory by default) Assuming you also have the span element for showing the validation errors along with your inputs.

    <form asp-action="Create" asp-controller="User" method="post">
    
        <input type="text" asp-for="Code" />
        <span asp-validation-for="Code" class="text-danger"></span>
    
        <input type="submit" />
    </form>
    

    These 2 files are dependent on jQuery. So make sure you included that script as well.