I have two Model Classes, Telephone and Telephone Model.
To create a new Telephone
it is necessary to choose a TelephoneModel
.
I want to add within the Telephone
Create View, a Modal to create a TelephoneModel
without having to leave the view.
Inside the TelephoneController
I already added a function that takes the data from the Modal and creates the TelephoneModel
in the database. This function is called with an Ajax from the Create View of Telephone
.
It correctly adds the TelephoneModel
to the BDD, but it doesn’t refresh my view.
How do I get the view to reload with the new information to choose from after creating the TelephoneModel
in the BDD?
Models:
namespace WebApplication1.Models
{
public class Telefono
{
[Key]
public int ID { get; set; }
public required string Nombre { get; set; }
public int IpId { get; set; }
public virtual Ip? Ip { get; set; }
public int ModeloTelefonoId { get; set; }
public ModeloTelefono? ModeloTelefono { get; set; }
}
public class ModeloTelefono
{
public int ID { get; set; }
public required string Nombre { get; set; }
public required int MarcaID { get; set; } // Required foreign key property
public Marca? Marca { get; set; } // Required reference navigation to principal
}
}
Function:
public async Task<IActionResult> AddModelo(string Modelo, int MarcaID, string Nombre, int subredID, int ipID)
{
var newModelo = new ModeloTelefono
{
Nombre = Modelo,
MarcaID = MarcaID
};
if (newModelo != null)
{
_context.Add(newModelo);
await _context.SaveChangesAsync();
ViewBag.SubReds = _context.SubRed.ToList();
ViewData["IpId"] = new SelectList(_context.Ip, "ID", "IpValue", ipID);
ViewData["SubRedes"] = new SelectList(_context.SubRed, "ID", "Nombre", subredID);
ViewData["ModeloTelefonoId"] = new SelectList(_context.ModeloTelefono, "ID", "Nombre", newModelo.ID);
ViewData["Marcas"] = new SelectList(_context.Marca, "ID", "Nombre");
return View("Create", new Telefono { Nombre = Nombre });
}
else { return View(); }
}
Ajax Function:
function agregarModelo() {
const Modelo = document.querySelector("#modeloInput").value
const MarcaID = document.querySelector("#marcaSelect").value;
const Nombre = document.querySelector("#Nombre").value;
const subredID = document.querySelector("#Ip_SubRedID").value;
const ipID = document.querySelector("#ipDropdown").value;
$.ajax({
url: '/Telefonoes/AddModelo',
type: 'POST',
dataType: 'JSON',
data: { Modelo: Modelo, MarcaID: MarcaID, Nombre: Nombre, subredID: subredID, ipID: ipID }
});
}