Is it possible to get standard ASP.NET MVC Unobtru

2020-03-28 17:46发布

问题:

I'm trying to build a custom module to integrate with Orchard CMS to implement a business application. While Orchard CMS is an MVC application, it doesn't seem possible (or, at least easy) to do all the things that can be done "out of the box" with MVC.

I'm trying to get unobtrusive validation to work on my view but can't seem to get this to work.

Update: As per Rohan West's advice below, I've now got the scripts included in the page using the ResourceManifest class and the Script.Require calls.

However, the validation attributes on the actual HTML elements are not being generated despite having the .NET attributes on my properties for which I'm using @Html.EditorFor on.

I have set the appSettings in the web.config file as follows:

<appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>      

    <add key="webpages:Enabled" value="false" />
    <add key="log4net.Config" value="Config\log4net.config" />
</appSettings>

Still no joy!

Update 2: As per Rohan West's suggestion, modifying the OrchardStarter class to comment out the following lines "solves" the problem:

    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(new LocalizedModelValidatorProvider());

There should be a better way of handling this though.

回答1:

You need to define the script in the resource manifest for your module.

public class ResourceManifest : IResourceManifestProvider
{
    public void BuildManifests(ResourceManifestBuilder builder)
    {
        var manifest = builder.Add();

        manifest.DefineScript("jQueryValidation").SetUrl("jquery.validate.js", "jquery.validate.min.js").SetVersion("1.7").SetDependencies("jQuery");
        manifest.DefineScript("jQueryValidation_Unobtrusive").SetUrl("jquery.validate.unobtrusive.js", "jquery.validate.unobtrusive.min.js").SetDependencies("jQuery", "jQueryValidation");
    }
} 

and then in your page

@{ 
    this.Script.Require("jQueryValidation_Unobtrusive").AtHead(); 
}

Have a look at the following class

Orchard.Environment.OrchardStarter

In Orchard 1.4.2 there is a line which removes all ModelValidatorProviders

ModelValidatorProviders.Providers.Clear();

This is removing the default DataAnnotationsModelValidatorProvider from the collection. You could try adding it to the collection,