Namespace name 'IndexModel' could not be found while running Entity Framework Core tutorial in ASP.NET Core - 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.

Related

DisplayNameFor doesn't lookup resx file despite IStringLocalizer and IHtmlLocalizer working correctly in the Razor page

I've got my Login.cshtml page
#page
#using Microsoft.AspNetCore.Mvc.Localization
#using Microsoft.Extensions.Localization
#inject IStringLocalizer<LoginModel> localizer
#inject IHtmlLocalizer<LoginModel> htmlLocalizer
#model LoginModel
<h1>#htmlLocalizer["Title"]</h1> TRANSLATES WELL
<h1>#localizer["Title"]</h1> TRANSLATES WELL
[...]
div class="checkbox">
<label asp-for="Input.RememberMe" class="form-label">
<input class="form-check-input" asp-for="Input.RememberMe" />
#Html.DisplayNameFor(m => m.Input.RememberMe) //DOESN'T WORK, DOESN'T LOOKUP RESX FILE
</label>
</div>
In the scaffolded Login.cshtml.cs page model there is an attribute [Display] fr the RememberMe property, but this one is not getting translated despite translation being put in the same resource file
/// <summary>
/// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
[Display(Name = "Remember")] //DOESN'T WORK, DOESN'T LOOKUP RESX FILE
public bool RememberMe { get; set; }
We can see that the structure is correct
Resx file itself:
This is what gets rendered:
Add data annotations localization in startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddDataAnnotationsLocalization(options => {
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(SharedResource));
});
}
This is Microsoft's bug which I reported: https://developercommunity.visualstudio.com/t/Custom-tool-cant-generate-designer-file/10213747?
Steps to reproduce:
Create ASP.Net Core MVC app Create resources directory Create resource
file called name.pl.resx Add few keypairs Build Expected behaviour:
Designer file is generate the resx file can be referenced as a type in
the code.
Actual behaviour: Error: Custom tool PublicResXFileCodeGenerator
failed to produce an output for input fileā€¦
Workaround: With each resx file edition
remove locale from its name Unload projectt Releoad project Clean
Build Rename resx file to contain locale again

How do I get the Web Root Path and the Content Root Path in ASP.NET Core?

I am trying to add a root path as a parameter in a View, so I can pass it as a parameter to a PayPal button.
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
... snip ...
<input type="hidden" name="return" value="#Model.UrlRoot/Manage/Subscription?userId=#Model.User.Id">
... snip ...
</form>
I was sifting through the answers at
How can I get my webapp's base URL in ASP.NET MVC? (20 answers)
and
ASP.NET MVC 6 application's virtual application root path
Since ASP.NET Core is quite different, the Request class no longer contains a .Url property, so most of those answers don't work.
You can inject the IHostingEnvironment into the Controller like this:
public class HomeController : Controller
{
protected readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
}
}
In your _ViewImports.cshtml add:
#using Microsoft.AspNetCore.Hosting
#inject IHostingEnvironment HostingEnvironment
Now you can use can use HostingEnvironment and all its properties in your form.
For example HostingEnvironment.WebRootPath or HostingEnvironment.ContentRootPath
I came across Marius Schulz's post. (If you are Marius, please add your answer, contact me and I'll remove mine.)
https://blog.mariusschulz.com/2016/05/22/getting-the-web-root-path-and-the-content-root-path-in-asp-net-core
For some reason my Controllers don't have the IHostingEnvironment injected in the constructor, but they do have the Request object.
In my Controller, I've declared
var urlRoot = $"{Request.Scheme}://{Request.Host}{Url.Content("~")}";
and passed it to MyViewModel
var model = new MyViewModel { UrlRoot = urlRoot };
return View(model);
This takes into account http vs. https, port numbers, and hopefully, the site root if the web site is not rooted at /. Since my site is at / I cannot confirm that Url.Content("~") gets the site root.
With .NET core 2.1 the context is automatically injected into views.
The base path of the request which displayed the view can be accessed like this:
#(Context.Request.PathBase)
In a net core 5 razor page, I added the following to the top of the page:
#inject IHostEnvironment hostEnvironment
then further down in my code, I used the following code with success:
string filePath = $#"{ hostEnvironment.ContentRootPath }\wwwroot\assets\img\users\{ user.ID }.jpg";
if (System.IO.File.Exists(filePath))
{
imageURL = $"{ user.ID }.jpg";
}

How do you create a confirmation message in .net Core 2.1 RazorPages?

Hopefully not a dumb question- I am rewriting an app from .net core mvc to .net core Razor. In MVC I use viewbags to create and display confirmation of actions being successful or display error message if not. Viewbags don't seem to be used or available in the same way for Razor pages in .net core 2.1.
How do you achieve the above in Razor pages? Any code snippets as example would be helpful. Thanks
We can use a Post-Redirect-Get pattern to display a message after an action.
Here is an example that uses TempData to store a message during a POST and then redirects to a GET. Using TempData to store the message is particularly appropriate for redirection, because the data only exists until something reads it.
SomePage.cshtml
#page
#model SomePageModel
#if(TempData[SomePageModel.MessageKey] is string message)
{
<p>#message</p>
}
<form method="POST">
<button type="submit">POST!</button>
</form>
SomePage.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace temp.Pages
{
public class SomePageModel : PageModel
{
public const string MessageKey = nameof(MessageKey);
public void OnGet() { }
public IActionResult OnPost() {
TempData[MessageKey] = "POST Success!";
return RedirectToAction(Request.Path); // redirect to the GET
}
}
}
This pattern also works for HTTP methods such as PUT and DELETE. Simply substitute any other HTTP verb; for instance, we can do a Put-Redirect-Get.

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; }
}

Migration from WCF WebApi to MVC4 Api - Registering global error handler

I am migrating a project that was developed using WebApi Preview 5 (when it was part of WCF) to the final release of WebApi (part of MVC4). There is a document describing the process but it is extremely simplistic and doesn't cover most of the issues.
Now one of the issues I am facing is that a GlobalErrorHandler was created by inheriting from HttpErrorHandler and then overriding OnTryProvideResponse and that was used to hook error handling with Elmah. Now that was registered on AppStart with a line like this:
var configuration = new WebApiConfiguration();
//some other configuration for security and CreateInstance
configuration.ErrorHandlers =
(handlers, endpoint, description) => handlers.Add(new GlobalErrorHandler())
};
//then some registration
RouteTable.Routes.MapServiceRoute<SomeObject>("routeName", configuration);
and then mapping different route to this configuration. All this code doesn't work in the new world of MVC4 WebApi, it seems like there is a conflict between HttpErrorHandler and it can't even implement its members properly.
Now I've seen general posts about how to register Elmah with WebApi but I am trying to stick to the original code as much as possible and I am assuming - may be I am wrong - that there is a direct equivalent to what Microsoft had in the Preview version and what they released in the final one. So my questions:
What is the equivalent of this Global Error handling registation in ASP.NET MVC4 WebApi?
Do I need to do the configuration the same way it is done here (default webapi samples project doesn't seem to have similar code)
What is the equivalent of that route registration line of code: RouteTable.Routes.MapServiceRoute("routeName", configuration);
If you create a quick one-off WebApi MVC project in Visual Studio you will see an App_Start folder which contains some classes which have static methods for handling the registration, specifically:
FilterConfig.cs
WebApiConfig.cs
WebApi Config is where you need to register routes etc...
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Filter config is what you need to handle your global errors... Filter config has a default error handler attribute added which you can swap out or out
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
Global.asax calls these static registration scripts like so:
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
In regard to Elmah it appears simplying including the Nuget package will register it...
Look for the package Elmah.Mvc
PM> Install-Package Elmah.MVC
it used to be like this How to get ELMAH to work with ASP.NET MVC [HandleError] attribute? but now according to this blog it has changed:
HandleErrorAttribute inside If you tried to use ELMAH in ASP.NET MVC,
you are probably implemented your own HandleErrorAttribute, as it's
shown in this example. You no longer need to apply this custom code
with Elmah.MVC. As soon you installed package, so can safely remove
your HandleError attribute, since it's already included into package.
This now appears to register itself in the Web.Config as a managedHandler so your code does not need to reference Elmah directly.