In my project I have a login and I want the username to be usable in the .cshtml
.
I have it in ASP.NET Core MVC mode and these are my files:
LoginModel.cs
namespace MVC_Catálogo_Imágenes.Models
{
public class LoginModel
{
[Required(ErrorMessage = "Campo obligatorio")]
public string? User { get; set; }
[Required(ErrorMessage = "Campo obligatorio")]
public string? Password { get; set; }
}
}
Controller.cs
:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel l)
{
try
{
using (SqlConnection con = new(_contexto.Valor))
{
using (SqlCommand cmd = new("sp_login", con))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("@Usuario", System.Data.SqlDbType.VarChar).Value = l.User;
cmd.Parameters.Add("@Pass", System.Data.SqlDbType.VarChar).Value = l.Password;
cmd.Parameters.Add("@Estado", System.Data.SqlDbType.Bit).Value = 1;
con.Open();
object result = cmd.ExecuteScalar();
int count = result == null ? 0 : Convert.ToInt32(result);
con.Close();
if (count > 0)
{
IsAuthenticated = true;
return RedirectToAction("Index", "Home");
}
else
{
ViewData["error"] = "Usuario y/o contraseña incorrectos";
return View();
}
}
}
}
catch (Exception)
{
ViewData["error2"] = "Ha habido un error al iniciar sesión";
return View();
}
}
Profile.cshtml
@model LoginModel
<h5>@Model.User</h5>
Well, when calling the model from the view, I get this error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get devolvió null.
(lambdar)
i fixed using cookies:
[HttpPost]
public ActionResult Login(LoginModel loginModel)
{
Response.Cookies.Append("un", loginModel.User);
return RedirectToAction("Index", "Home");
}
public ActionResult Profile()
{
var model = new LoginModel
{
User = Request.Cookies["un"]
};
return View(model);
}