Return values to the controller in the model from the ASP.NET MVC view

When we create an ASP.NET MVC web application, the model (an object) is the easiest way to return values from the view to the controller.

For the view to be able to return the values in the model, make sure the model contains properties, not fields, for every value with { get; set; }

public class MyViewModel
{
    public string ID { get; set; }
}

Add the model to the view at the top of the .cshtml file

IMPORTANT!!! To return values for properties that do not have controls on the page, like IDs that are not displayed, add a hidden field to the view.

@model MyViewModel
<form  asp-action="Index" asp-controller="My">
    <input asp-for=@Model.ID type="hidden" >
</form>

Send the data in the model to the view from the get method in the controller

public class MyController : Controller
{
    public IActionResult Index()
    {
         MyViewModel model = new MyViewModel();
         model.ID = "MY_ID";
         return View(model);
    }
}

Read the value from the model in the post method of the controller and send the model back

public class MyController : Controller
{
    [HttpPost, ValidateAntiForgeryToken]
    public IActionResult Index(MyViewModel model)
    {
        string ID = model.ID;
...
        return View(model);
    }
}

 

.NET Framework Detection in the Windows Registry

To determine which .NET framework is installed on the Windows computer check the values in the registry.

The HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full key contains two values you can check:

  • Release
  • Version

You can use InSpec, part of the Chef DK, to check the values:

describe registry_key('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full') do
  it { should have_property 'Release' }
  it { should have_property_value('Release', :dword, 460805) } # For dword use the decimal value, no quotes
end

describe registry_key('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full') do
  it { should have_property 'Version' }
  it { should have_property_value('Version', :string, '4.7.02053') }
end
.NET version Release hexadecimal Release decimal Version
4.6.2 60636 394806 4.6.01590
4.7 70805 460805 4.7.02053
4.7.1 709FE 461310 4.7.02558

For more information see

https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed

 

Procedure or function ‘`…_Insert`’ cannot be found in database …

When you use the Microsoft .NET Entity framework to access a MySql database, the autogenerated code throws an error when you try to insert a row into the database with

context.MY_TABLE.Add(MY_OBJECT);

Server Error in ‘/’ Application.
Procedure or function ‘`…_Insert`’ cannot be found in database ‘`…`’.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: MySql.Data.MySqlClient.MySqlException: Procedure or function ‘`…_Insert`’ cannot be found in database ‘`…`’.

The auto-generated class tries to use stored procedures to update the database. To use the Entity Framework Linq commands, comment out the line that contains “MapToStoredProcedures”

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     base.OnModelCreating(modelBuilder);
     // modelBuilder.Entity<twitter_keywords>().MapToStoredProcedures();
 }

 

 

No connection string named ‘…’ could be found in the application config file.

Two-tier applications separate the presentation layer and the data layer, and all database access related objects are located in the data-tier.

When the application runs, the config file of the main project is read. In web applications, it is the web.config, in console applications the app.config file.

When you get the following runtime exception

Exception thrown: ‘System.InvalidOperationException’ in EntityFramework.dll
An exception of type ‘System.InvalidOperationException’ occurred in EntityFramework.dll but was not handled in user code
No connection string named ‘…Entities’ could be found in the application config file.

 

  1. Copy the connection string from the app.config file of the data-tier to the main project’s config file.
 <add name="USC_SocialMediaMSSQLEntities" connectionString="metadata=res://*/USC_SocialMedia_MSSQL.csdl|res://*/USC_SocialMedia_MSSQL.ssdl|res://*/USC_SocialMedia_MSSQL.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MY_SERVER;initial catalog=MY_DATABASE;user id=MY_USER;password=MY_PASWORD;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

2. This is a sample data access class in the data-layer to read data from the aspNetRoles table.

using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SocialMedia_Data {
	public class SocialMediaData {

		private USC_SocialMediaMSSQLEntities _web;

		public SocialMediaData() {

			// Set up the database connections
			_web = new USC_SocialMediaMSSQLEntities();

		}

		/// Returns the list of Roles
		public List GetRoles() {

			IEnumerable foundRoles = from aspNetRoles in _web.AspNetRoles
						 orderby aspNetRoles.DisplayOrder
						 select aspNetRoles;

			if (null == foundRoles || 0 == foundRoles.Count()) {
				return null;
			}

			return foundRoles.ToList();

		}
	}
}

NotSupportedException: Unable to determine the provider name for provider factory of type ‘MySql.Data.MySqlClient.MySqlClientFactory’. Make sure that the ADO.NET provider is installed or registered in the application config

In a two-tier web application, the data layer is in a separate project. This allows better separation between the presentation layer and the data layer. This way you can reuse the data project in another application that targets the same database.

To access a MySql database you need to add the MySql.Data and MySql.Data.Entity NuGet packages to the data project.

When you develop a two-tier application that targets a MySql database you may get the runtime error

NotSupportedException: Unable to determine the provider name for provider factory of type ‘MySql.Data.MySqlClient.MySqlClientFactory’. Make sure that the ADO.NET provider is installed or registered in the application config.

Even if all database interaction is handled in the data project, and you added the MySql NuGet packages to it, you need to add the MySql.Data and MySql.Data.Entity NuGet packages to the web project too, because the Web.config file contains the connection string that includes the reference to MySql.Data.MySqlClient.

<add name="MY_CONNECTION_NAME" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;port=3306;database=MY_DATABASE;uid=MY_USERNAME;password=MY_PASSWORD" />

At the time of writing do not use version 6.10.6.0 of the packages, it causes the error

Exception thrown: ‘System.TypeLoadException’ in mscorlib.dll
An exception of type ‘System.TypeLoadException’ occurred in mscorlib.dll but was not handled in user code
Inheritance security rules violated by type: ‘MySql.Data.MySqlClient.MySqlProviderServices’. Derived types must either match the security accessibility of the base type or be less accessible.

Until a new, corrected version is published, install version 6.9.11.0 of both packages in both projects.

For more information on how to connect to a MySql database from Visual Studio see Connect to a MySQL database from Visual Studio 2017

 

 

The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

When I made changes to the web.config file of an ASP.Net C# application, I have accidentally deleted a comma, and I started to get the runtime error message:

The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

Make sure all necessary commas are there in the config files, Visual Studio does not check the format of those lines. In my case, the error was in

<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />

The .NET MVC model has to have a parameterless constructor

When you create a class to be used as the model in a .NET MVC application, the class has to have a parameterless constructor. It is called during the POST when the user clicks the submit button of the form. If the class does not have a parameterless constructor, we will get the following generic error message. None of the breakpoints can help you to find the cause, and there is no entry in the event log.

The website cannot display the page
HTTP 500

Most likely causes:
•The website is under maintenance.
•The website has a programming error.

What you can try:
Refresh the page.
Go back to the previous page.
More information

No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer

When you move your Visual Studio solution to another workstation you may encounter the following error message:

System.Data.Entity.Core.MappingException was unhandled by user code
HResult=-2146232032
Message=Schema specified is not valid. Errors:
: error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer …
Source=EntityFramework

 

In this case it may help if you re-import the database objects into the .edmx file.

To import all objects again:

  • Open the .edmx file,
  • Press the Ctrl-A keys to select all tables in the diagram,
  • Press the delete key on the keyboard to delete all tables,
  • Right click the white area and select Model Browser,
  • In the Model Browser expand the {model name}.Store, and the Stored Procedures / Functions element
  • Delete all functions and stored procedures
  • In the {model name} element (the element above the {model name}.Store) expand the Function Imports element
  • Delete all function imports
  • Save the .edmx file
  • Right click the white area of the .edmx file and select Update Model from Database
  • Select all necessary tables, stored procedures, and functions and import them.

If you re-import the tables, but do not delete the stored procedures, functions, and function imports you may get the following error message:

HResult=-2146233079
Message=The function import ‘Tobacco_WebEntities.spGetAgeGroupId’ cannot be executed because it is not mapped to a store function.
Source=EntityFramework

 

Save the key file password in Visual Studio

When you have already set up the project signing of the C# application for ClickOnce deployment, and move the solution to another workstation you may get the following error message when you build the solution:

Severity Code Description Project File Line Suppression State
Error Cannot import the following key file: .....pfx. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name: VS_KEY_....

We get this message, because the new workstation does not know the key file password. To solve this problem, we have to save the key file password on the new workstation.

To make your solution work again

  • Open the Visual Studio project properties window,
  • On the Signing tab click the pull down that shows the name of the key file.
  • Select Browse,
  • Select the key file,
  • Enter the password in the Password text box.