M-V-C Fool-proof not working and showing Uncaught error? - foolproof-validation

I installed Fool-Proof from nuGet, but its not working uncaught errors.
Install-Package foolproof -Version 0.9.4518
As I installed it, new folder with name Clients Scripts gets added in to my project with three libraries: FoolProof Unobtrusive, FoolProof jQuery Validation and FoolProof Validation. Then I create new bundle in bundle.config and linked with my shared layout.
public bool active { get; set; }
[RequiredIf("active", true,ErrorMessage = "Code is Required")]
public int Code { get; set; }
It's not displaying validation message. Now, when I checked my console I am getting following errors:

You haven't loaded required js files. Add the following in BundleConfig.js
bundles.Add(new ScriptBundle("~/bundles/mvcfoolproof").Include(
"~/Scripts/MicrosoftAjax.js",
"~/Scripts/MicrosoftMvcAjax.js",
"~/Scripts/MicrosoftMvcValidation.js",
"~/Client Scripts/mvcfoolproof.unobtrusive.min.js",
"~/Client Scripts/MvcFoolproofJQueryValidation.min.js",
"~/Client Scripts/MvcFoolproofValidation.min.js"));
and then include in your View in correct order
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/mvcfoolproof")

Related

.AddRazorRuntimeCompilation() results in The type or namespace name 'IWebHostEnvironment' could not be found

In a .NET 6 / ASP.NET Core app after adding the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation Nuget package and adding
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
I get this error, when opening a view:
The type or namespace name 'IWebHostEnvironment' could not be found (are you missing a using directive or an assembly reference?)
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral("\n\n</html>\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public IWebHostEnvironment HostingEnv { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
IWebHostEnvironment is referenced in _Layout.cshtml:
#inject IWebHostEnvironment HostingEnv
<!DOCTYPE html>
<html lang="en">
...
</html>
Note:
The accepted answer works, however, Rider (and maybe ReSharper) might mark Microsoft.AspNetCore.Hosting. in the #inject statement as redundant.
I don't know why this happens, but I added this above the #inject statement line:
#* ReSharper disable once RedundantNameQualifier *#
Also, read my comment regarding the IsDevelopment() error I got after using the full qualified reference.
Have you tried fully qualifying the namespace and making it
#inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnv
If that works then I recall there being a difference in how _ViewImports files are processed during runtime compilation versus standard, it doesn’t cascade the same way. You may therefore find that your existing _ViewImports files aren’t all being read.

Namespace name 'IndexModel' could not be found while running Entity Framework Core tutorial in ASP.NET Core

I am trying to follow this tutorial from Microsoft:
Razor Pages with Entity Framework Core in ASP.NET Core - Tutorial 1 of 8:
[https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-5.0&tabs=visual-studio]
I created the project correctly, but i can't run the project because when i replace the copied code from this step in tutorial "Set up the site style" in my project: Views/Home/Index.cshtml and I try to run is showing me:
The type or namespace name 'IndexModel' could not be found...
The problem seems to be here:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
Where is this model I can't find it, I just created the application, and the model does not exist? Or I pasted in the wrong file because in tutorial is saying: "Pages/Index.cshtml, replace the contents of the file with the following code:" I can't find neither "Pages" folder?
Apparently the screenshot on the page is misleading, because there is a selected MVC project while this tutorial needs to work in a "Web app" without MVC. I didn't see a point above where it says to select "Web app" without MVC, the mistake was mine but the picture is also misleading. I believe many people have slipped into this mistake.
The screenshot
In your sample project, you should have:
Index.cshtml
Index.cshtml.cs
The Index.cshtml.cs might appear nested under Index.cshtml (so expand that).
Check that the Index.cshtml.cs includes something like this:
namespace ContosoUniversity.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
You can see that this is where your IndexModel is declared.
Did you rename the page Index.cshtml? Did you rename or delete Index.cshtml.cs?
The .cs is called "code behind" because its the code that supports the .cshtml file.

Failed to get the culture Resource in .net 3.1

Good morning,
I'm using .netCore 3.1 and in my model I have the attributeValidation of email, but the return message is always for default, I can't get the message in the expected culture.
I think that the structure folders is correct and when I inspect the middleware the resource base have this route:
Someone have any idea?
Thanks!!
I'm using .netCore 3.1 and in my model I have the attributeValidation of email, but the return message is always for default, I can't get the message in the expected culture.
I did a test with following code snippet, which work as expected, you can refer to it.
My testing model class under Models folder
public class MyModel
{
[Required(ErrorMessage = "The Email field is required")]
[EmailAddress(ErrorMessage = "The Email field is not a valid email address")]
[Display(Name = "Email")]
public string Email { get; set; }
//...
//other properties
//...
}
My resource file MyModel.fr.resx and folder structure
Configure localization
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddControllersWithViews().AddDataAnnotationsLocalization()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
Test Result
Besides, you can refer to this doc about "globalization and localization in ASP.NET Core" and try these steps to troubleshoot the issue.
check if you correctly configure localization and data annotations localization in your app
check if browser user select and set language/culture
check if you correctly use the dot or path naming convention to organize/name your resource file(s)

How can we enable caching for Bundles in MVC5

I have created 2 bundles in my mvc project as given below:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/Scripts/BaseScripts").Include(
"~/Content/js/jquery-{version}.js",
"~/Content/js/jquery-ui-{version}.js",
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Content/js/bootstrap.js",
"~/Content/js/bootstrap-datepicker.js",
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.js",
"~/Scripts/customvalidation.js"
)
);
bundles.Add(new ScriptBundle("~/Scripts/CustomScripts").Include(
"~/Content/js/customscripts/commonscript.js",
"~/Content/js/customscripts/registration.js"
));
bundles.Add(new StyleBundle("~/Styles/Css").Include(
"~/Content/css/bootstrap.min.css",
"~/Content/css/ymobiz.css",
"~/Content/css/Style.css",
"~/Content/css/datepicker3.css",
"~/Content/font-awesome-4.1.0/css/font-awesome.min.css",
"~/Content/css/css.css"
));
//To enable bundling and minification
BundleTable.EnableOptimizations = true;
}
Now i need to enable caching for these files as well. Is there any way by which we can control caching duration for these bundles files
MVC bundles are returned as a single static file to browsers whose cache time is set to 1 year by default. ASP.NET MVC takes care of change tracking of your bundle files and changes bundle url if content of any file is changed or a file is being added / removed from bundle.
As bundles are already cached and change tracking is maintained by asp.net mvc framework, what else cache control do you want on those bundles?
EDIT (in response to comment)
Unfortunately you can not alter that limit. Cache limit is handles by ProcessRequest method of BundleHandler class and this is internal sealed so there is no chance that you can inherit \ override these requests.
For further details you can refer this question.
Add a key in webconfig
<appSettings>
<add key="Version" value="sa291988" />
</appSettings>
Create a class, where we define the format for both JavaScript and styles.
using System.Configuration;
namespace BundlingSample
{
public class SiteKeys {
public static string StyleVersion {
get {
return "<link href=\"{0}?v=" +
ConfigurationManager.AppSettings["version"] + "\" rel=\"stylesheet\"/>";
}
}
public static string ScriptVersion {
get {
return "<script src=\"{0}?v=" +
ConfigurationManager.AppSettings["version"] + "\"></script>";
}
}
}
}
#Styles.RenderFormat(SiteKeys.StyleVersion,"~/Content/css")
#Scripts.RenderFormat(SiteKeys.ScriptVersion,"~/bundles/jquery")

MVC SQL No Connection String Named Could Be Found in the Application Config File EF6

I have searched through a number of questions(No Connection String Named MyEntities Could Be Found In The Application Config), but most seem to deal with multiple projects in a solution, in this case I have only one project in one solution. Also this is my first MVC Project with EF6. When going to add a controller I get this error:
This is my Web.Config
And This is My Solution Explorer
I know the error references an Application Config File, but I do not have an app Config file, nor do I know where to put it or how to create it.
EDIT, Here is the code for the db context
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("name=DBConnection"){}
public System.Data.Entity.DbSet<zzz.Models.Supplier> Suppliers { get; set; }
}