admin管理员组

文章数量:1122846

To give you some context I am currently working on an MVC project and I seem to be stuck in what to do in order to create a form that will receive information about the Person, like name, last name and such, as well as user info, username.. password.

Now the problem is that I have created both of these data set as different entities meaning there is an Username Entity as well as a Person Entity. And I want both of them to be Created through the same view.

I am literally lost in how this is made.

These are the relevant controllers, models and Views I made:

// Person Class:

public class Persona
{
    public int Id { get; set; }
    public string Nombre { get; set; }
    public string ApellidoPaterno { get; set; }
    public string ApellidoMaterno { get; set; }
    public string Email { get; set; }
    public string Telefono { get; set; }
    

    //Relationship
    
    public int UsuarioId { get; set; }
    public Usuario Usuario { get; set; }
    
    
}

// User Class:

public class Usuario
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    
    //Relacion
    public int PersonaId { get; set; }
    public Persona Persona { get; set; }
    
}

The Create from the Persona Controller:

  //POST CREATE
    [HttpPost]
    public async Task<IActionResult> Create([Bind("Id,Nombre,ApellidoPaterno, ApellidoMaterno, Email, Telefono")] Persona persona)
    {
        if (ModelState.IsValid)
        {
            _context.Add(persona);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(persona);
    }

And its view:

@model Persona

<p>Crear nueva Persona</p>

<form asp-controller="Persona" method="post">
    <div>
        <label asp-for="Nombre">Nombre</label>
        <input type="text" asp-for="Nombre">
        <span asp-validation-for="Nombre"></span>

    </div>
    <div>
        <label asp-for="ApellidoPaterno">Apellido Paterno</label>
        <input type="text" asp-for="ApellidoPaterno">
        <span asp-validation-for="ApellidoPaterno"></span>
    </div>
    <div>
        <label asp-for="ApellidoMaterno">Apellido Materno</label>
        <input type="text" asp-for="ApellidoMaterno">
        <span asp-validation-for="ApellidoMaterno"></span>

    </div>
    <div>
        <label asp-for="Email">Email</label>
        <input type="text" asp-for="Email">
        <span asp-validation-for="Email"></span>
    </div>
    <div>
        <label asp-for="Telefono">Telefono</label>
        <input type="text" asp-for="Telefono">
        <span asp-validation-for="Telefono"></span>
    </div>
    <input type="submit" value="Crear Nuevo">
</form>

In the past I have used ViewData in order to display certain info of another Entity in the View. But I believe for this situation that wouldn't help as I am trying to create a new entry in the DB.

If anyone knows any guidance or good resources towards learning how to deal with these relationships in an .NET MVC manner I would highly appreciate it!

Thank you for your time.

To give you some context I am currently working on an MVC project and I seem to be stuck in what to do in order to create a form that will receive information about the Person, like name, last name and such, as well as user info, username.. password.

Now the problem is that I have created both of these data set as different entities meaning there is an Username Entity as well as a Person Entity. And I want both of them to be Created through the same view.

I am literally lost in how this is made.

These are the relevant controllers, models and Views I made:

// Person Class:

public class Persona
{
    public int Id { get; set; }
    public string Nombre { get; set; }
    public string ApellidoPaterno { get; set; }
    public string ApellidoMaterno { get; set; }
    public string Email { get; set; }
    public string Telefono { get; set; }
    

    //Relationship
    
    public int UsuarioId { get; set; }
    public Usuario Usuario { get; set; }
    
    
}

// User Class:

public class Usuario
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    
    //Relacion
    public int PersonaId { get; set; }
    public Persona Persona { get; set; }
    
}

The Create from the Persona Controller:

  //POST CREATE
    [HttpPost]
    public async Task<IActionResult> Create([Bind("Id,Nombre,ApellidoPaterno, ApellidoMaterno, Email, Telefono")] Persona persona)
    {
        if (ModelState.IsValid)
        {
            _context.Add(persona);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(persona);
    }

And its view:

@model Persona

<p>Crear nueva Persona</p>

<form asp-controller="Persona" method="post">
    <div>
        <label asp-for="Nombre">Nombre</label>
        <input type="text" asp-for="Nombre">
        <span asp-validation-for="Nombre"></span>

    </div>
    <div>
        <label asp-for="ApellidoPaterno">Apellido Paterno</label>
        <input type="text" asp-for="ApellidoPaterno">
        <span asp-validation-for="ApellidoPaterno"></span>
    </div>
    <div>
        <label asp-for="ApellidoMaterno">Apellido Materno</label>
        <input type="text" asp-for="ApellidoMaterno">
        <span asp-validation-for="ApellidoMaterno"></span>

    </div>
    <div>
        <label asp-for="Email">Email</label>
        <input type="text" asp-for="Email">
        <span asp-validation-for="Email"></span>
    </div>
    <div>
        <label asp-for="Telefono">Telefono</label>
        <input type="text" asp-for="Telefono">
        <span asp-validation-for="Telefono"></span>
    </div>
    <input type="submit" value="Crear Nuevo">
</form>

In the past I have used ViewData in order to display certain info of another Entity in the View. But I believe for this situation that wouldn't help as I am trying to create a new entry in the DB.

If anyone knows any guidance or good resources towards learning how to deal with these relationships in an .NET MVC manner I would highly appreciate it!

Thank you for your time.

Share Improve this question asked Nov 22, 2024 at 8:11 yzkaelyzkael 1578 bronze badges 1
  • NB: Based on the entities, you appear to be storing your users' passwords in plain text. Don't do that! Store a salted hash of the password, using a unique salt per record. – Richard Deeming Commented Nov 22, 2024 at 10:40
Add a comment  | 

1 Answer 1

Reset to default 1

I would generally create a viewmodel to represent the properties you want to edit, and use that to create or update the entities.

For example:

public class PersonaViewModel
{
    // For editing an existing record:
    public PersonaViewModel(Persona persona)
    {
        Id = persona.Id;
        Nombre = persona.Nombre;
        ApellidoPaterno = persona.ApellidoPaterno;
        ApellidoMaterno = persona.ApellidoMaterno;
        Email = persona.Email;
        Telefono = persona.Telefono;
        Username = persona.Usuario.Username;
        Password = persona.Usuario.Password;
    }
    
    // Needed for model binding:
    public PersonaViewModel()
    {
    }
    
    public int Id { get; set; }
    public string Nombre { get; set; }
    public string ApellidoPaterno { get; set; }
    public string ApellidoMaterno { get; set; }
    public string Email { get; set; }
    public string Telefono { get; set; }
    
    public string Username { get; set; }
    public string Password { get; set; }
    
    public void UpdateEntity(Persona persona)
    {
        persona.Nombre = Nombre;
        persona.ApellidoPaterno = ApellidoPaterno;
        persona.ApellidoMaterno = ApellidoMaterno;
        persona.Email = Email;
        persona.Telefono = Telefono;
        
        persona.Usuario ??= new();
        persona.Usuario.Username = Username;
        persona.Usuario.Password = Password;
    }
}
[HttpGet]
public IActionResult Create()
{
    PersonaViewModel personaModel = new();
    return View(personaModel);
}

[HttpPost]
public async Task<IActionResult> Create(PersonaViewModel personaModel)
{
    if (!ModelState.IsValid) return View(personaModel);
    
    Persona persona = new();
    personaModel.UpdateEntity(persona);
    
    _context.Persona.Add(persona);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

[HttpGet]
public async Task<IActionResult> Edit(int personaId)
{
    Persona persona = await _context.Persona.Include(p => p.Usuario)
        .FirstOrDefaultAsync(p => p.Id == personaId);
    
    if (persona is null) return RedirectToAction(nameof(Index));
    
    PersonaViewModel personaModel = new(persona);
    return View(personaModel);
}

[HttpPost]
public async Task<IActionResult> Edit(PersonaViewModel personaModel)
{
    Persona persona = await _context.Persona.Include(p => p.Usuario)
        .FirstOrDefaultAsync(p => p.Id == personaModel.Id);
    
    if (persona is null) return RedirectToAction(nameof(Index));
    if (!ModelState.IsValid) return View(personaModel);
    
    personaModel.UpdateEntity(persona);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}
@model PersonaViewModel

<p>Crear nueva Persona</p>

<form asp-controller="Persona" method="post">
    <!-- Not strictly necessary for creating, but needed for editing: -->
    <input type="hidden" asp-for="Id">
    
    <div>
        <label asp-for="Nombre">Nombre</label>
        <input type="text" asp-for="Nombre">
        <span asp-validation-for="Nombre"></span>
    </div>
    <div>
        <label asp-for="ApellidoPaterno">Apellido Paterno</label>
        <input type="text" asp-for="ApellidoPaterno">
        <span asp-validation-for="ApellidoPaterno"></span>
    </div>
    <div>
        <label asp-for="ApellidoMaterno">Apellido Materno</label>
        <input type="text" asp-for="ApellidoMaterno">
        <span asp-validation-for="ApellidoMaterno"></span>
    </div>
    <div>
        <label asp-for="Email">Email</label>
        <input type="text" asp-for="Email">
        <span asp-validation-for="Email"></span>
    </div>
    <div>
        <label asp-for="Telefono">Telefono</label>
        <input type="text" asp-for="Telefono">
        <span asp-validation-for="Telefono"></span>
    </div>
    <div>
        <label asp-for="Username">Username</label>
        <input type="text" asp-for="Username">
        <span asp-validation-for="Username"></span>
    </div>
    <div>
        <label asp-for="Password">Password</label>
        <input type="text" asp-for="Password">
        <span asp-validation-for="Password"></span>
    </div>
    <input type="submit" value="Crear Nuevo">
</form>

本文标签: cHow can I make a Create Razor View for a RelationshipStack Overflow