Two models and one controller

1

Following the reasoning this my other question , where I create two models for manipulations, how could I use a controller to do the manipulations in the tables?

My intention in doing this is that in the same view I can make a record of both information at once. Because I did not want to create a controller to make changes to the phone table, but to the student controller .

Is this feasible? If not, could I use AJAX and if possible, examples?

    
asked by anonymous 06.11.2014 / 19:29

1 answer

1
  

... could I use a controller to do the manipulations in the tables?

Actually the controller does not manipulate tables.

Commenting very roughly, the controller receives the requests from the GET / POST user, maps to Action and returns a View . You do not have any responsibility to manipulate tables, this would be a responsibility of your Model .

So you can for example:

1- Create a class called AlunoViewModel, which will be a kind of container of all the desired information for the student's registration (for example: name, phone, address, etc.). This class may have a method to save the student.

public class AlunoViewModel
{    
    [Required]
    public string Nome { get; set; }

    [DisplayName("Endereço")]
    public string Endereco { get; set; }

    [DisplayName("Telefone")]
    public string NumeroTelefone { get; set; }

    public ICollection<Telefone> Telefones {get;set;}

    // Demais propriedades

    // Método para salvar um aluno
    public static void Salvar(AlunoViewModel alunoViewModel)
    {
        //Seu código para salvar uma aluno
    }
}

2- Create a controller and enter Actions (one to display the "GET" sign-up screen, another to receive the "POST"

public class AlunoController: Controller
{
    public ActionResult Criar()
    {                    
       return View(new AlunoViewModel());
    }

    [HttpPost]
    public ActionResult Criar(AlunoViewModel alunoViewModel)
    {           
        //Agora usando as informações de alunoViewModel você chama o seu Model para criar os objetos (aluno, telefone, etc) e salvar no banco.
        AlunoViewModel.Salvar(alunoViewModel);
    }
}

3- Create the View of type AlunoViewModel to be displayed in the registry.

@model Models.AlunoViewModel    
@{
    ViewBag.Title = "Cadastro de Aluno";        
}

 @*

   Aqui vai o código em razor para exibir as informações do cadastro

*@

Yes, it is feasible to record the student's phone information, parents, etc. whether using AJAX or not.

In the case of registering the student's phones, you can have a PhoneNumber property (for example, a textbox control) and a button for the user to add the phone to the list. example). As soon as the user enters the number, clicking the button, you add the informed phone in the ListBox (related to the Telephones property). In the post on the registration screen you will receive this list of phones and associate the student to save.

    
06.11.2014 / 21:23