How can I occupy a model several times in asp.net core?

1

What happens is that I create a model of each table in my sql server database and a context of all tables with Scaffold-DbContext "my string" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context TrabajoContext, After I occupy only the model of the User table, with that I create a login and everything goes well, I create a session with HttpContext.Session.SetString, when entering with the login, but in my model I only use the Required in the two fields that I use for the login, which are the password and the mail, when I enter and make a form to register more users, at the moment of putting all the fields in the Required, the login stops working, because it requires the other fields of the model . My question is how I can occupy the same model so that only occupies these two fields in the login and then entering the session can occupy all the fields to insert more users.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace TRABAJO.Models
{
    public partial class Usuario
    {
        public Usuario()
        {
            Agenda = new HashSet<Agenda>();
        }
        //si pongo un [Required] en cualquiera que no sea correo o contraseña mi login deja de servir
        public string Curp { get; set; }
        public string Matricula { get; set; }
        public string Nombre { get; set; }
        public string ApPat { get; set; }
        public string ApMat { get; set; }
        public string Direcciom { get; set; }
        public string NumExterior { get; set; }
        public string NumInterior { get; set; }
        public int CodigoPostal { get; set; }
        public string Colonia { get; set; }
        public string Demarcacion { get; set; }
        public string EntidadFederativa { get; set; }
        public string Foto { get; set; }
        [Required(ErrorMessage = "Se requiere de la contraseña")]
        [DataType(DataType.Password)]
        public string Contrasena { get; set; }
        public int Status { get; set; }
        public DateTime CreatedUs { get; set; }
        [Required(ErrorMessage = "Se requiere el usuario")]
        public string Correo { get; set; }
        public int IdTipoTrabajor { get; set; }

        public TipoTrabajor IdTipoTrabajorNavigation { get; set; }
    }
}

Controller

 [HttpPost]
        public ActionResult Login(Usuario user)
        {
            if(ModelState.IsValid)
            {
                var account = _context.Usuario.Where(u => u.Correo == user.Correo && u.Contrasena == user.Contrasena).FirstOrDefault();
                if(account != null)
                {
                    HttpContext.Session.SetString("Curp", account.Curp.ToString());
                    HttpContext.Session.SetString("Nombre", account.Nombre.ToString());
                    return RedirectToAction("Welcome");
                }
                else
                {
                    ModelState.AddModelError("", "El usuario o la contraseña son incorrectos.");
                }
            }
            return View();


        }
public ActionResult RegisterU(Usuario user)
        {
            if (ModelState.IsValid)
            {
                _context.Usuario.Add(user);
                _context.SaveChanges();

                ModelState.Clear();
                ViewBag.Message = user.Nombre + " " + user.ApPat + " " + "registrado con exito.";
            }

            return View();
        }

View

@model TRABAJO.Models.Usuario
@{ 
    ViewData["Title"] = "Login";
}

<h2>Login</h2>
<form class="form-horizontal" asp-controller="Home" asp-action="Login" method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Correo" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Correo" class="form-control" />
            <span asp-validation-for="Correo" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="Contrasena" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Contrasena" class="form-control" />
            <span asp-validation-for="Contrasena" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <button type="submit" class="btn btn-success">Iniciar</button>
        </div>
    </div>
</form>

I'm a rookie in asp.net core, I only used mvc in php and I just started using .net

    
asked by Karla Huerta 23.01.2018 в 23:35
source

1 answer

2

You can add a class just for the login, in fact you can see that creating a new project gives you the option to create it with individual authentication accounts and then use the class in the table to register the users and a class to the beginning of session something like this would be:

public class LoginViewModel
    {
        [Required]
        [Display(Name = "Correo")]

        public string Correo{ get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Contraseña")]
        public string Contrasena{ get; set; }

    }

View

in the line where you make use of the user model, you change it by LoginViewModel

  

@model WORK.Models.LoginViewModel

@model TRABAJO.Models.LoginViewModel
@{ 
    ViewData["Title"] = "Login";
}

<h2>Login</h2>
<form class="form-horizontal" asp-controller="Home" asp-action="Login" method="post">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Correo" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Correo" class="form-control" />
            <span asp-validation-for="Correo" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="Contrasena" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Contrasena" class="form-control" />
            <span asp-validation-for="Contrasena" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <button type="submit" class="btn btn-success">Iniciar</button>
        </div>
    </div>
</form>

Controller

We change the received model that you have usuario by which we create InicioSesion that's how you compare it within the controller

  

public ActionResult Login (LoginViewModel HomeSession)

 [HttpPost]
        public ActionResult Login(LoginViewModel InicioSesion)
        {
            if(ModelState.IsValid)
            {
            var account = _context.Usuario.Where(u => u.Correo == InicioSesion.Correo && u.Contrasena == InicioSesion.Contrasena).FirstOrDefault();
                if(account != null)
                {
                    HttpContext.Session.SetString("Curp", account.Curp.ToString());
                    HttpContext.Session.SetString("Nombre", account.Nombre.ToString());
                    return RedirectToAction("Welcome");
                }
                else
                {
                    ModelState.AddModelError("", "El usuario o la contraseña son incorrectos.");
                }
            }
            return View();


        }

the class you can add it in the models folder

    
answered by 24.01.2018 / 00:04
source