1

I am struggling to persist the new data to the database because I can't find the proper ApplicationDbContext method. First of all, let me show you the steps that led to this. The following method shows how got the necessary fields from the Db in order to fill in the fields in the Edit view.

 public ActionResult UsersWithRoles()
    {
        var usersWithRoles = (from user in context.Users
                              select new
                              {
                                  UserId = user.Id,
                                  Username = user.UserName,
                                  Email = user.Email,
                                  RoleNames = (from userRole in user.Roles
                                               join role in context.Roles on userRole.RoleId
                                               equals role.Id
                                               select role.Name).ToList()
                              }).ToList().Select(p => new UserViewModels()

                              {
                                  UserId = p.UserId,
                                  Username = p.Username,
                                  Email = p.Email,
                                  Role = string.Join(",", p.RoleNames)
                              });


        return View(usersWithRoles);
    }

This works fine, the view looks like this:

Edit

Right. Now, if I click "Save", this is the method that is supposed to pass the new data to the database:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(UserViewModels user)
    {
        if (ModelState.IsValid)
        {
            context.Update(user);
            await context.SaveChangesAsync();
            return null;
        }
        return null;

    }

In the tutorial that I've followed, context.Update was used - however, in my case, it says that ApplicationDbContext does not have a method called Update. Also, return RedirectToAction does not work because

it can not convert System.Web.Mvc.RedirectToRouteResult to Microsoft.AspNetCore.Mvc.IActionResult

How should the latter method be written in order to work properly?

csproj info:

    <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />
  <Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
  <Import Project="..\packages\EntityFramework.6.3.0\build\EntityFramework.props" Condition="Exists('..\packages\EntityFramework.6.3.0\build\EntityFramework.props')" />
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{96AED44B-7760-489B-BC37-21451980A753}</ProjectGuid>
    <ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>ARA_Tool</RootNamespace>
    <AssemblyName>ARA Tool</AssemblyName>
    <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
    <MvcBuildViews>false</MvcBuildViews>
    <UseIISExpress>true</UseIISExpress>
    <Use64BitIISExpress />
    <IISExpressSSLPort>44365</IISExpressSSLPort>
    <IISExpressAnonymousAuthentication />
    <IISExpressWindowsAuthentication />
    <IISExpressUseClassicPipelineMode />
    <UseGlobalApplicationHostFile />
    <NuGetPackageImportStamp>
    </NuGetPackageImportStamp>
    <TypeScriptToolsVersion>3.5</TypeScriptToolsVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
      <HintPath>..\packages\EntityFramework.6.3.0\lib\net45\EntityFramework.dll</HintPath>
    </Reference>
    <Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
      <HintPath>..\packages\EntityFramework.6.3.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNet.Identity.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNet.Identity.Core.2.2.3\lib\net45\Microsoft.AspNet.Identity.Core.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.3\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNet.Identity.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNet.Identity.Owin.2.2.3\lib\net45\Microsoft.AspNet.Identity.Owin.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNetCore.Http.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNetCore.Http.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Abstractions.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNetCore.Http.Features, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNetCore.Http.Features.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.Features.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNetCore.Mvc.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNetCore.Mvc.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Abstractions.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.AspNetCore.Routing.Abstractions, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.AspNetCore.Routing.Abstractions.2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Routing.Abstractions.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="Microsoft.Extensions.Primitives, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Extensions.Primitives.2.2.0\lib\netstandard2.0\Microsoft.Extensions.Primitives.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Net.Http.Headers, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Net.Http.Headers.2.2.0\lib\netstandard2.0\Microsoft.Net.Http.Headers.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.4.1.0\lib\net45\Microsoft.Owin.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Host.SystemWeb, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Host.SystemWeb.4.1.0\lib\net45\Microsoft.Owin.Host.SystemWeb.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.4.1.0\lib\net45\Microsoft.Owin.Security.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security.Cookies, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.Cookies.4.1.0\lib\net45\Microsoft.Owin.Security.Cookies.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security.Facebook, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.Facebook.4.1.0\lib\net45\Microsoft.Owin.Security.Facebook.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security.Google, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.Google.4.1.0\lib\net45\Microsoft.Owin.Security.Google.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security.MicrosoftAccount, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.MicrosoftAccount.4.1.0\lib\net45\Microsoft.Owin.Security.MicrosoftAccount.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security.OAuth, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.OAuth.4.1.0\lib\net45\Microsoft.Owin.Security.OAuth.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security.Twitter, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.Twitter.4.1.0\lib\net45\Microsoft.Owin.Security.Twitter.dll</HintPath>
    </Reference>
    <Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Buffers.4.5.0\lib\netstandard2.0\System.Buffers.dll</HintPath>
    </Reference>
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Memory, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Memory.4.5.1\lib\netstandard2.0\System.Memory.dll</HintPath>
    </Reference>
    <Reference Include="System.Numerics" />
    <Reference Include="System.Numerics.Vectors, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
    </Reference>
    <Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.5.1\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
    </Reference>
    <Reference Include="System.Text.Encodings.Web, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
      <HintPath>..\packages\System.Text.Encodings.Web.4.5.0\lib\netstandard2.0\System.Text.Encodings.Web.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.DynamicData" />
    <Reference Include="System.Web.Entity" />
    <Reference Include="System.Web.ApplicationServices" />
    <Reference Include="System.ComponentModel.DataAnnotations" />
    <Reference Include="System.Core" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Web" />
    <Reference Include="System.Web.Extensions" />
    <Reference Include="System.Web.Abstractions" />
    <Reference Include="System.Web.Routing" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Configuration" />
    <Reference Include="System.Web.Services" />
    <Reference Include="System.EnterpriseServices" />
    <Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <Private>True</Private>
      <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
    </Reference>
    <Reference Include="System.Net.Http">
    </Reference>
    <Reference Include="System.Net.Http.WebRequest">
    </Reference>
    <Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <Private>True</Private>
      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.Helpers.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <Private>True</Private>
      <HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.7\lib\net45\System.Web.Mvc.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Optimization">
      <HintPath>..\packages\Microsoft.AspNet.Web.Optimization.1.1.3\lib\net40\System.Web.Optimization.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <Private>True</Private>
      <HintPath>..\packages\Microsoft.AspNet.Razor.3.2.7\lib\net45\System.Web.Razor.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <Private>True</Private>
      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.WebPages.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.WebPages.Deployment, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <Private>True</Private>
      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <Private>True</Private>
      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.7\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
    </Reference>
    <Reference Include="WebGrease">
      <Private>True</Private>
      <HintPath>..\packages\WebGrease.1.6.0\lib\WebGrease.dll</HintPath>
    </Reference>
    <Reference Include="Antlr3.Runtime">
      <Private>True</Private>
      <HintPath>..\packages\Antlr.3.5.0.2\lib\Antlr3.Runtime.dll</HintPath>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Owin">
      <HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security.Cookies">
      <HintPath>..\packages\Microsoft.Owin.Security.Cookies.4.0.0\lib\net451\Microsoft.Owin.Security.Cookies.dll</HintPath>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="App_Start\BundleConfig.cs" />
    <Compile Include="App_Start\FilterConfig.cs" />
    <Compile Include="App_Start\IdentityConfig.cs" />
    <Compile Include="App_Start\RouteConfig.cs" />
    <Compile Include="App_Start\Startup.Auth.cs" />
    <Compile Include="Controllers\AccountController.cs" />
    <Compile Include="Controllers\HomeController.cs" />
    <Compile Include="Controllers\ManageController.cs" />
    <Compile Include="Controllers\ManageUsersController.cs" />
    <Compile Include="Global.asax.cs">
      <DependentUpon>Global.asax</DependentUpon>
    </Compile>
    <Compile Include="Models\AccountViewModels.cs" />
    <Compile Include="Models\IdentityModels.cs" />
    <Compile Include="Models\ManageViewModels.cs" />
    <Compile Include="Models\UserViewModels.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="Startup.cs" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="Content\bootstrap-theme.css" />
    <Content Include="Content\bootstrap-theme.min.css" />
    <Content Include="Content\bootstrap.css" />
    <Content Include="Content\bootstrap.min.css" />
    <Content Include="favicon.ico" />
    <Content Include="fonts\glyphicons-halflings-regular.svg" />
    <Content Include="Global.asax" />
    <Content Include="Content\Site.css" />
    <Content Include="Scripts\bootstrap.js" />
    <Content Include="Scripts\bootstrap.min.js" />
    <Content Include="Scripts\esm\popper-utils.js" />
    <Content Include="Scripts\esm\popper-utils.min.js" />
    <Content Include="Scripts\esm\popper.js" />
    <Content Include="Scripts\esm\popper.min.js" />
    <Content Include="Scripts\index.js.flow" />
    <Content Include="Scripts\esm\popper.min.js.map" />
    <Content Include="Scripts\esm\popper.js.map" />
    <Content Include="Scripts\esm\popper-utils.min.js.map" />
    <Content Include="Scripts\esm\popper-utils.js.map" />
    <Content Include="fonts\glyphicons-halflings-regular.woff2" />
    <Content Include="fonts\glyphicons-halflings-regular.woff" />
    <Content Include="fonts\glyphicons-halflings-regular.ttf" />
    <Content Include="fonts\glyphicons-halflings-regular.eot" />
    <Content Include="Content\bootstrap.min.css.map" />
    <Content Include="Content\bootstrap.css.map" />
    <Content Include="Content\bootstrap-theme.min.css.map" />
    <Content Include="Content\bootstrap-theme.css.map" />
    <None Include="Scripts\jquery-3.4.1.intellisense.js" />
    <Content Include="Scripts\jquery-3.4.1.js" />
    <Content Include="Scripts\jquery-3.4.1.min.js" />
    <Content Include="Scripts\jquery-3.4.1.slim.js" />
    <Content Include="Scripts\jquery-3.4.1.slim.min.js" />
    <None Include="Scripts\jquery.validate-vsdoc.js" />
    <Content Include="Scripts\jquery.validate.js" />
    <Content Include="Scripts\jquery.validate.min.js" />
    <Content Include="Scripts\jquery.validate.unobtrusive.js" />
    <Content Include="Scripts\jquery.validate.unobtrusive.min.js" />
    <Content Include="Scripts\modernizr-2.8.3.js" />
    <Content Include="Scripts\popper-utils.js" />
    <Content Include="Scripts\popper-utils.min.js" />
    <Content Include="Scripts\popper.js" />
    <Content Include="Scripts\popper.min.js" />
    <Content Include="Scripts\src\index.js" />
    <Content Include="Scripts\src\methods\defaults.js" />
    <Content Include="Scripts\src\methods\destroy.js" />
    <Content Include="Scripts\src\methods\disableEventListeners.js" />
    <Content Include="Scripts\src\methods\enableEventListeners.js" />
    <Content Include="Scripts\src\methods\placements.js" />
    <Content Include="Scripts\src\methods\update.js" />
    <Content Include="Scripts\src\modifiers\applyStyle.js" />
    <Content Include="Scripts\src\modifiers\arrow.js" />
    <Content Include="Scripts\src\modifiers\computeStyle.js" />
    <Content Include="Scripts\src\modifiers\flip.js" />
    <Content Include="Scripts\src\modifiers\hide.js" />
    <Content Include="Scripts\src\modifiers\index.js" />
    <Content Include="Scripts\src\modifiers\inner.js" />
    <Content Include="Scripts\src\modifiers\keepTogether.js" />
    <Content Include="Scripts\src\modifiers\offset.js" />
    <Content Include="Scripts\src\modifiers\preventOverflow.js" />
    <Content Include="Scripts\src\modifiers\shift.js" />
    <Content Include="Scripts\src\utils\clockwise.js" />
    <Content Include="Scripts\src\utils\computeAutoPlacement.js" />
    <Content Include="Scripts\src\utils\debounce.js" />
    <Content Include="Scripts\src\utils\find.js" />
    <Content Include="Scripts\src\utils\findCommonOffsetParent.js" />
    <Content Include="Scripts\src\utils\findIndex.js" />
    <Content Include="Scripts\src\utils\getBordersSize.js" />
    <Content Include="Scripts\src\utils\getBoundaries.js" />
    <Content Include="Scripts\src\utils\getBoundingClientRect.js" />
    <Content Include="Scripts\src\utils\getClientRect.js" />
    <Content Include="Scripts\src\utils\getFixedPositionOffsetParent.js" />
    <Content Include="Scripts\src\utils\getOffsetParent.js" />
    <Content Include="Scripts\src\utils\getOffsetRect.js" />
    <Content Include="Scripts\src\utils\getOffsetRectRelativeToArbitraryNode.js" />
    <Content Include="Scripts\src\utils\getOppositePlacement.js" />
    <Content Include="Scripts\src\utils\getOppositeVariation.js" />
    <Content Include="Scripts\src\utils\getOuterSizes.js" />
    <Content Include="Scripts\src\utils\getParentNode.js" />
    <Content Include="Scripts\src\utils\getPopperOffsets.js" />
    <Content Include="Scripts\src\utils\getReferenceNode.js" />
    <Content Include="Scripts\src\utils\getReferenceOffsets.js" />
    <Content Include="Scripts\src\utils\getRoot.js" />
    <Content Include="Scripts\src\utils\getRoundedOffsets.js" />
    <Content Include="Scripts\src\utils\getScroll.js" />
    <Content Include="Scripts\src\utils\getScrollParent.js" />
    <Content Include="Scripts\src\utils\getStyleComputedProperty.js" />
    <Content Include="Scripts\src\utils\getSupportedPropertyName.js" />
    <Content Include="Scripts\src\utils\getViewportOffsetRectRelativeToArtbitraryNode.js" />
    <Content Include="Scripts\src\utils\getWindow.js" />
    <Content Include="Scripts\src\utils\getWindowSizes.js" />
    <Content Include="Scripts\src\utils\includeScroll.js" />
    <Content Include="Scripts\src\utils\index.js" />
    <Content Include="Scripts\src\utils\isBrowser.js" />
    <Content Include="Scripts\src\utils\isFixed.js" />
    <Content Include="Scripts\src\utils\isFunction.js" />
    <Content Include="Scripts\src\utils\isIE.js" />
    <Content Include="Scripts\src\utils\isModifierEnabled.js" />
    <Content Include="Scripts\src\utils\isModifierRequired.js" />
    <Content Include="Scripts\src\utils\isNumeric.js" />
    <Content Include="Scripts\src\utils\isOffsetContainer.js" />
    <Content Include="Scripts\src\utils\removeEventListeners.js" />
    <Content Include="Scripts\src\utils\runModifiers.js" />
    <Content Include="Scripts\src\utils\setAttributes.js" />
    <Content Include="Scripts\src\utils\setStyles.js" />
    <Content Include="Scripts\src\utils\setupEventListeners.js" />
    <Content Include="Scripts\umd\popper-utils.js" />
    <Content Include="Scripts\umd\popper-utils.min.js" />
    <Content Include="Scripts\umd\popper.js" />
    <Content Include="Scripts\umd\popper.min.js" />
    <Content Include="Web.config" />
    <Content Include="Web.Debug.config">
      <DependentUpon>Web.config</DependentUpon>
    </Content>
    <Content Include="Web.Release.config">
      <DependentUpon>Web.config</DependentUpon>
    </Content>
    <Content Include="Views\Web.config" />
    <Content Include="Views\_ViewStart.cshtml" />
    <Content Include="Views\Shared\Error.cshtml" />
    <Content Include="Views\Shared\_Layout.cshtml" />
    <Content Include="Views\Home\About.cshtml" />
    <Content Include="Views\Home\Contact.cshtml" />
    <Content Include="Views\Home\Index.cshtml" />
    <Content Include="Views\Account\_ExternalLoginsListPartial.cshtml" />
    <Content Include="Views\Account\ConfirmEmail.cshtml" />
    <Content Include="Views\Account\ExternalLoginConfirmation.cshtml" />
    <Content Include="Views\Account\ExternalLoginFailure.cshtml" />
    <Content Include="Views\Account\ForgotPassword.cshtml" />
    <Content Include="Views\Account\ForgotPasswordConfirmation.cshtml" />
    <Content Include="Views\Account\Login.cshtml" />
    <Content Include="Views\Account\Register.cshtml" />
    <Content Include="Views\Account\ResetPassword.cshtml" />
    <Content Include="Views\Account\ResetPasswordConfirmation.cshtml" />
    <Content Include="Views\Account\SendCode.cshtml" />
    <Content Include="Views\Account\VerifyCode.cshtml" />
    <Content Include="Views\Manage\AddPhoneNumber.cshtml" />
    <Content Include="Views\Manage\ChangePassword.cshtml" />
    <Content Include="Views\Manage\Index.cshtml" />
    <Content Include="Views\Manage\ManageLogins.cshtml" />
    <Content Include="Views\Manage\SetPassword.cshtml" />
    <Content Include="Views\Manage\VerifyPhoneNumber.cshtml" />
    <Content Include="Views\Shared\Lockout.cshtml" />
    <Content Include="Views\Shared\_LoginPartial.cshtml" />
    <Content Include="Scripts\umd\popper.min.js.map" />
    <Content Include="Scripts\umd\popper.js.map" />
    <Content Include="Scripts\umd\popper.js.flow" />
    <Content Include="Scripts\umd\popper-utils.min.js.map" />
    <Content Include="Scripts\umd\popper-utils.js.map" />
    <Content Include="Scripts\README.md" />
    <Content Include="Scripts\popper.min.js.map" />
    <Content Include="Scripts\popper.js.map" />
    <Content Include="Scripts\popper-utils.min.js.map" />
    <Content Include="Scripts\popper-utils.js.map" />
    <Content Include="Views\ManageUsers\UsersWithRoles.cshtml" />
    <Content Include="Views\ManageUsers\Edit.cshtml" />
    <Content Include="Views\ManageUsers\CreateUser.cshtml" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="App_Data\" />
  </ItemGroup>
  <ItemGroup>
5
  • What is the type of your context variable? IdentityDbContext or DbContext? Commented Dec 6, 2019 at 16:15
  • What is the version of asp.net are you using? Commented Dec 6, 2019 at 16:16
  • It is IdentityDbContext. As for the version, I suppose it's 2.2.6 Commented Dec 6, 2019 at 16:19
  • I'm busy now to answer with a good example. But you can follow Travis answer. If have any problem I can provide an answer latter. Commented Dec 6, 2019 at 17:09
  • @LuttiCoelho I followed Travis' answer but couldn't find a way. Please check my reply on his post out and perhaps give me some tips to fix the issues. Commented Dec 7, 2019 at 16:46

2 Answers 2

4

You are parsing your ORM generated user model into a self defined viewModel, asking the user to edit it then expecting your DB context to automagically convert it back over and save. Your DB context has no automatic concept of how to convert your viewmodel back to your model. It is just an abstract class mapping over your database. You have to explicitly do that yourself or explore options such as auto-mapper to map the two classes together.

A quick non-tested example on your high level object

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(UserViewModels user)
{
    if (ModelState.IsValid)
    {

      var u = context.Users.where(a => a.Id == UserId).FirstOrDefault();
      if(u != null)
      {
        u.UserName = user.UserName
        so on.....
        await context.SaveChangesAsync();
        return RedirectToAction("CompleteActionName");
      }

        return RedirectToAction("UserNotFound", user);
    }
    return View(user);

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your example. I am sorry I couldn't come back with an answer earlier. I am having two issues - first would be how can I access the AspNetUserRoles table in order to change the role of a certain user? Secondly, I am still having issues with the RedirectToAction and View methods because they can not be converted from Web.Mvc.RedirectToRouteResult to AspNetCore.Mvc.IActionResult. Could you give me some tips to solve these two issues, please?
An update for the statement above: I removed the Async things and I fixed the RedirectToAction part. However, I am still having issues passing the updated Role.
1

The first problem, like @TravisActon said is that your are expecting that EF auto convert the UserViewModels class to IdentityUser. You can do exactly as Travis explained at his answer. I just want to give you a second option. Using UserManager class that gives you a lot of functions to handle users and roles.

Case you are using Asp.Net Framework with OWIN Pretty sure you are.

First add this using on your controller:

using Microsoft.AspNet.Identity.Owin;

Then make a few change on your method:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(UserViewModels userViewModel)
{
    if (!ModelState.IsValid)
        return View(userViewModel);

    // Get UserManager from OwinContext needs "using Microsoft.AspNet.Identity.Owin;"
    var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

    var appUser = await userManager.FindByIdAsync(userViewModel.UserId);
    if (appUser == null)
        return await Task.Run<ActionResult>(() => RedirectToAction("UserNotFound", userViewModel));

    appUser.UserName = userViewModel.Username;
    appUser.Email = userViewModel.Email;

    // Updates the user information with UserManager
    await userManager.UpdateAsync(appUser);

    // Get all roles from user.
    var currentUserRoles = await userManager.GetRolesAsync(appUser.Id);

    // Remove all current roles fro this user. You can skip it if you don't need it.
    var removeCurrentRolesResult = await userManager.RemoveFromRolesAsync(appUser.Id, currentUserRoles.ToArray());

    // Verify if any error occours
    if(!removeCurrentRolesResult.Succeeded)
    {
        // Add errors to ModelState.
        removeCurrentRolesResult.Errors.ToList().ForEach(error => ModelState.AddModelError("Role", error));

        return View(userViewModel);
    }

    // get userRoles from text to an array of string;
    var newRoles = userViewModel.Role.Split(',').Select(_ => _.Trim());

    // Adds user to the new role
    var addRoleResult = await userManager.AddToRolesAsync(appUser.Id, newRoles.ToArray());

    if (!addRoleResult.Succeeded)
    {
          // handle errors like removeCurrentRolesResult
          return View(userViewModel);
    }

    return await Task.Run<ActionResult>(() => RedirectToAction("UsersWithRoles"));
}

Case you are using Asp.Net Core 2+

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit([FromService] UserManager userManager, UserViewModels userViewModel)
{
    if (!ModelState.IsValid)
        return View(userViewModel);

    var userModel = await userManager.FindByIdAsync(userViewModel.Id);
    if(userModel == null)
    {
        return await Task.Run<ActionResult>(() => RedirectToAction("UserNotFound", userViewModel));
    }

    // Updates the user information with UserManager
    userManager.SetUserNameAsync(userModel, userViewModel.UserName);
    userManager.SetEmailAsync(userModel, userViewModel.Email);

    // Get all roles from user.
    var currentUserRoles = await userManager.GetRolesAsync(userModel);

    // Remove all current roles fro this user. You can skip it if you don't need it.
    var removeCurrentRolesResult = await userManager.RemoveFromRolesAsync(appUser, currentUserRoles);

    // Verify if any error occours
    if(!removeCurrentRolesResult.Succeeded)
    {
        // Add errors to ModelState.
        removeCurrentRolesResult.Errors.ToList().ForEach(t => ModelState.AddModelError("Role", t.Description));

        return View(userViewModel);
    }

    // get userRoles from text to an array of string;
    var newRoles = userViewModel.Roles.Split(',').Select(_ => _.Trim());

    // Adds user to the new role
    var addRoleResult = await _userManager.AddToRolesAsync(userModel, newRoles);

    if (!addRoleResult.Succeeded)
    {
      // handle errors like removeCurrentRolesResult
      return View(userViewModel);
    }


    // Return redirect to action object without need to remove async from method.
    return await Task.Run<ActionResult>(() => RedirectToAction("UserNotFound", userModel));
}

The second problem, with redirects, is because RedirectToAction is an IActionResult and your method returns a Task<IActionResult> so to solve this you need to change return type of your method to IActionResult or call RedirectToAction into an async call. Like this:

return await Task.Run<ActionResult>(() => RedirectToAction("ActionName", model));

13 Comments

Thanks for your answer. Unfortunately, I have a few issues: The first one is that [FromService] attribute could not be found. Is it something that can be used only in AspNetCore? Secondly, line return await Task.Run<IActionResult>(() => RedirectToAction("UserNotFound", userViewModel)); returns the error cannot convert lambda expression to type because it is not a delegate type. Moreover, it also couldn't find the method SetUserNameAsync, whereas SetEmailAsync worked. Lastly, variable appUser was not found. What exactly should it be? Thank you for any help regarding this issue!
[FromService] only works at Asp.net core. As you said you are using version 2.2.6 I imagine that's your asp.net core version.
appUser was my mistake. It should be userModel. I'll fix it on my answer
@Questieme I already updated my answer with a solution for Asp.Net Framework version. I'm pretty sure that will solve your problem.
And please let's keep all code needed to solve any problem inside stack overflow. We'll help more people this way.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.