Two Models in an MVC view 5

0

I have two Models:

public class Solicitudes
{
    public int SolicitudesID { get; set; }
    public DateTime FechaEmision { get; set; }
    public DateTime FechaInicio { get; set; }
    public DateTime FechaFin { get; set; }
    public string Observacion { get; set; }
    public int UsuariosID { get; set; }
    public int TipoSolicitudesID { get; set; }
    public int CondicionesID { get; set; }
}

public class Condiciones
{
    [Key]
    public int CondicionesID { get; set; }
    public string NombreCondiciones { get; set; }
    public int EstadoCondiciones { get; set; }

}

If you can help me say how I do to appear in a view. the Class Requests as independent fields and Conditions within a radiobuttonfor by means of a foreach. At the end all the fields must be registered in a table. And how would you receive the controller?

//POST
    [HttpPost]
    public ActionResult Create(Solicitudes solicitud)
    {
        if (ModelState.IsValid)
        {

        }
        return View(solicitud);
    }

I'm learning asp.net mvc, please help.

    
asked by Luis Vega 09.10.2017 в 23:30
source

2 answers

1

It is not possible to have more than one model in a view, but what you can do is create a model that contains those two models:

namespace NombreDeTuProyyecto.Models
{
    public class Modelos
    {
        public List<Solicitudes> { get; set; }
        public List<Condiciones> { get; set; }
    }
}

In the view you should refer to the model you are going to work with:

@model NombreDeTuProyyecto.Models.Modelos
//Iteración del modelo suponiendo que deseas llenar una tabla:

<tbody>
    @foreach (var item in Model.Solicitudes)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.SolicitudesID)
            </td>
        </tr>
    }
</tbody>

In the Controller, in the same way, you can receive the model you are working with:

public ActionResult AlgunaAccion(Modelos modelos)
{
    if (ModelState.IsValid)
    {
        //Acciones y operaciones a realizar
        return RedirectToAction("Index");
    }
}
    
answered by 09.10.2017 в 23:47
0

You can create an ViewModel and reference it to the model of the view:

  

A viewModel is responsible for implementing the behavior of the   view to respond to the user's actions and to expose the data   of the model in such a way that it is easy to use the data loads in the view.

public class tuViewModel
{
    public Solicitudes solicitudes;
    public Condiciones condiciones;
}

On your controller load the same viewModel

[HttpPost]
    public ActionResult Create(tuViewModel objViewModel)
    {
        if (ModelState.IsValid)
        {

        }
        return View(objViewModel);
    }

And in the view the object reference

@model esquemaDelViewModel.tuViewModel

As you start, I recommend you Learn MVC.Net

    
answered by 09.10.2017 в 23:44