Estaba probando mi aplicación al insertar datos y editarlos, pero me di cuenta que en la tabla AspNetUsers solo se estaban insertando los datos de un solo usuario, los demás usuarios permanecen únicamente con los datos con los que se registraron en el sistema (Nombre, apellido, email y contraseña). La aplicación no me lanza ningun error y todo parece estar bien, pero al momento de querer guardar los datos, no hace nada, y los Inputs donde vienen todos los datos desde la vista regresan vacíos, a excepción de uno de los usuarios registrados en la base en el sistema.
Aquí está el codigo de la vista:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UniJobs.Data;
using UniJobs.Models;
namespace UniJobs.Areas.Identity.Pages.Account.Manage
{
public partial class IndexModel : PageModel
{
private readonly UserManager<Usuarios> _userManager;
private readonly SignInManager<Usuarios> _signInManager;
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _webHostEnvironment;
public IndexModel(
UserManager<Usuarios> userManager,
SignInManager<Usuarios> signInManager,
ApplicationDbContext context,
IWebHostEnvironment webHostEnvironment)
{
_userManager = userManager;
_signInManager = signInManager;
this._context = context;
this._webHostEnvironment = webHostEnvironment;
}
public string Username { get; set; }
[TempData]
public string StatusMessage { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public class InputModel
{
[Display(Name = "Imagen de perfil")]
public IFormFile InputImagen { get; set; }
[Display(Name = "¿Quién Soy?")]
public string QuienSoy { get; set; }
[Display(Name = "Sobre mis habilidades")]
public string SobreHabilidades { get; set; }
[Display(Name = "Sobre mis aptitudes")]
public string SobreAptitudes { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Nombre")]
public string FirstName { get; set; }
[Display(Name = "Provincia")]
public int? Provincia { get; set; }
[Display(Name = "Mi universidad")]
public int? MiUni { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Apellido")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Fecha de nacimiento")]
public DateTime? BirthDate { get; set; }
[Phone]
[Display(Name = "Phone number")]
public string PhoneNumber { get; set; }
}
private async Task LoadAsync(Usuarios user)
{
var userName = await _userManager.GetUserNameAsync(user);
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
user.ID_Uni = _context.ListaEstudiantesUniversidades.Where(U => U.FK_UsuarioID == user.Id)
.Select(U => U.FK_UniversidadID).FirstOrDefault();
Username = userName;
Input = new InputModel
{
FirstName = user.FirstName,
LastName = user.LastName,
BirthDate = user.BirthDate,
Provincia = user.FK_ProvinciaID,
PhoneNumber = phoneNumber,
MiUni = user.ID_Uni,
QuienSoy = user.QuienSoy,
SobreHabilidades = user.SobreHabilidades,
SobreAptitudes = user.SobreAptitudes
};
}
public async Task<IActionResult> OnGetAsync()
{
ViewData["FK_ProvinciaID"] = new SelectList(_context.Provincias, "ProvinciasID", "Provincia");
ViewData["Universidad"] = new SelectList(_context.Universidades, "UniversidadesID", "NombreUniversidad");
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
await LoadAsync(user);
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadAsync(user);
return Page();
}
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
if (Input.PhoneNumber != phoneNumber)
{
var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
StatusMessage = "Unexpected error when trying to set phone number.";
return RedirectToPage();
}
}
if (Input.InputImagen != null)
{
//Save image to wwwroot/image
string wwwRootPath = _webHostEnvironment.WebRootPath;
string ImageName = Path.GetFileNameWithoutExtension(Input.InputImagen.FileName);
string ExtensionImage = Path.GetExtension(Input.InputImagen.FileName);
user.ProfileImage = ImageName = ImageName + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ExtensionImage;
string path = Path.Combine(wwwRootPath + "/UsersImages/Users/", ImageName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await Input.InputImagen.CopyToAsync(fileStream);
}
//Insert record
}
if (Input.MiUni != _context.ListaEstudiantesUniversidades.Where(U => U.FK_UsuarioID == user.Id)
.Select(U => U.FK_UniversidadID).FirstOrDefault())
{
var UniID = _context.ListaEstudiantesUniversidades.Where(U => U.FK_UsuarioID == user.Id)
.Select(U => U.ListaEstudiantesUniversidadesID).FirstOrDefault();
var StudentUni = await _context.ListaEstudiantesUniversidades.FindAsync(UniID);
_context.ListaEstudiantesUniversidades.Remove(StudentUni);
await _context.SaveChangesAsync();
var Uni = _context.ListaEstudiantesUniversidades.Add(new ListaEstudiantesUniversidades
{
FK_UniversidadID = Input.MiUni.Value,
FK_UsuarioID = user.Id
});
await _context.SaveChangesAsync();
}
if (Input.FirstName != user.FirstName)
{
user.FirstName = Input.FirstName;
}
if (Input.LastName != user.LastName)
{
user.LastName = Input.LastName;
}
if (Input.BirthDate != user.BirthDate)
{
user.BirthDate = Input.BirthDate;
}
if (Input.Provincia != user.FK_ProvinciaID)
{
user.FK_ProvinciaID = Input.Provincia;
}
if (Input.QuienSoy != user.QuienSoy)
{
user.QuienSoy = Input.QuienSoy;
}
if (Input.SobreHabilidades != user.SobreHabilidades)
{
user.SobreHabilidades = Input.SobreHabilidades;
}
if (Input.SobreAptitudes != user.SobreAptitudes)
{
user.SobreAptitudes = Input.SobreAptitudes;
}
await _userManager.UpdateAsync(user);
await _signInManager.RefreshSignInAsync(user);
StatusMessage = "Your profile has been updated";
return RedirectToPage();
}
}
}
Aquí está la vista:
@page
@model IndexModel
@{
ViewData["Title"] = "Profile";
ViewData["ActivePage"] = ManageNavPages.Index;
}
<div id="content-wrapper" class="d-flex flex-column">
<partial name="_StatusMessage" model="Model.StatusMessage" />
<!-- Main Content -->
<div id="content">
<!-- Begin Page Content -->
<section class="bg-light" style="padding: 1em 0;">
<div class="container">
<div class="row">
<div class="col-12">
<form id="profile-form" method="post" enctype="multipart/form-data" class="p-5 bg-white user">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="row form-group mb-4">
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Input.FirstName"></label></h3>
<input type="text" asp-for="Input.FirstName" class="form-control form-control-user">
<span asp-validation-for="Input.FirstName" class="text-danger"></span>
</div>
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Input.LastName"></label></h3>
<input type="text" asp-for="Input.LastName" class="form-control form-control-user">
<span asp-validation-for="Input.LastName" class="text-danger"></span>
</div>
</div>
<div class="row form-group mb-4">
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Input.PhoneNumber"></label></h3>
<input type="text" asp-for="Input.PhoneNumber" class="form-control form-control-user">
<span asp-validation-for="Input.PhoneNumber" class="text-danger"></span>
</div>
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Username"></label></h3>
<input type="text" asp-for="Username" class="form-control form-control-user">
</div>
</div>
<div class="row form-group mb-4">
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Input.BirthDate"></label></h3>
<input asp-for="Input.BirthDate" class="form-control form-control-user">
<span asp-validation-for="Input.BirthDate" class="text-danger"></span>
</div>
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Input.Provincia"></label></h3>
<select asp-for="Input.Provincia" class="form-control" asp-items="ViewBag.FK_ProvinciaID">
<option>Provincia...</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Input.MiUni"></label></h3>
<select asp-for="Input.MiUni" class="form-control" asp-items="ViewBag.Universidad">
<option>Universidades...</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<h3><label asp-for="Input.QuienSoy"></label></h3>
</div>
<div class="col-md-12 mb-3 mb-md-0">
<textarea name="Input.QuienSoy" asp-for="Input.QuienSoy" class="form-control" id="" cols="30" rows="5"></textarea>
<span asp-validation-for="Input.QuienSoy" class="text-danger"></span>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<h3><label asp-for="Input.SobreHabilidades"></label></h3>
</div>
<div class="col-md-12 mb-3 mb-md-0">
<textarea name="Input.SobreHabilidades" asp-for="Input.SobreHabilidades" class="form-control" id="" cols="30" rows="5"></textarea>
<span asp-validation-for="Input.SobreHabilidades" class="text-danger"></span>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<h3><label asp-for="Input.SobreAptitudes"></label></h3>
</div>
<div class="col-md-12 mb-3 mb-md-0">
<textarea name="Input.SobreAptitudes" asp-for="Input.SobreAptitudes" class="form-control" id="" cols="30" rows="5"></textarea>
<span asp-validation-for="Input.SobreAptitudes" class="text-danger"></span>
</div>
</div>
<div class="row form-group mb-4">
<div class="col-md-6 mb-3 mb-md-0">
<h3><label asp-for="Input.InputImagen"></label></h3>
<input asp-for="Input.InputImagen" accept="image/*">
<span asp-validation-for="Input.InputImagen" class="text-danger"></span>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<button id="update-profile-button" type="submit" class="btn btn-primary py-2 px-5">Guardar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Y aquí está el modelo:
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace UniJobs.Models
{
public class Usuarios : IdentityUser
{
[Required(ErrorMessage = "El campo {0} es requerido. Favor llenar.")]
[Display(Name = "Nombre")]
[PersonalData]
public string FirstName { get; set; }
[Required(ErrorMessage = "El campo {0} es requerido. Favor llenar.")]
[Display(Name = "Apellido")]
[PersonalData]
public string LastName { get; set; }
#nullable enable
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[PersonalData]
[Column(TypeName = "date")]
[DataType(DataType.Date)]
[Display(Name = "Fecha de nacimiento")]
public DateTime? BirthDate { get; set; }
[Display(Name = "Imagen de perfil")]
[PersonalData]
public string? ProfileImage { get; set; }
[Display(Name = "¿Quién Soy?")]
[PersonalData]
public string? QuienSoy { get; set; }
[Display(Name = "Sobre mis habilidades")]
[PersonalData]
public string? SobreHabilidades { get; set; }
[Display(Name = "Sobre mis aptitudes")]
[PersonalData]
public string? SobreAptitudes { get; set; }
#nullable disable
[PersonalData]
[Display(Name = "Fecha de creación")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[Column(TypeName = "date")]
[DataType(DataType.Date)]
public DateTime DateCreated { get; set; }
[Display(Name = "Provincia")]
[PersonalData]
public int? FK_ProvinciaID { get; set; }
[ForeignKey("FK_ProvinciaID")]
public Provincias Provincias { get; set; }
[NotMapped]
public string DateString { get; set; }
public Usuarios()
{
Roles = new List<string>();
EmpresaUser = new List<Empresas>();
}
[NotMapped]
public IList<string> Roles { get; set; }
[NotMapped]
public IList<Empresas> EmpresaUser { get; set; }
[NotMapped]
public int ID_Uni { get; set; }
[NotMapped]
public string Provincia { get; set; }
}
}