Multiple models in an ASP NET MVC view [duplicated]

0

Hello friends I'm still stuck with this, someone can help me out ... This is my error:

These are my models and my htmlCs

//kyo es el nombre de mi vista, este es el controller
        //GET: Home/kyo
        [Authorize]
        public ActionResult Kyo( )
        {
            
              return View();
        }

With this I am calling the models I want my data from

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PCotiza_compras.Models;


namespace PCotiza_compras.Models
{
    public class ReqCatDep
    {
        public List<PCotiza_compras.Models.Departments> Dep { get; set; }
        public List<PCotiza_compras.Models.Categories> Cat { get; set; }
        public List<PCotiza_compras.Models.Requests> Req { get; set; }

    }
}

And this is my view:

@model PCotiza_compras.Models.ReqCatDep

@{
    ViewBag.Title = "Kyo";
}


<div class="panel-group" id="accordion">
  <td>

      @foreach (var item in Model.Cat)
      {
          <tr>
              @item.Name
          </tr>
          <tr>
              @item.Description
          </tr>
      }

     
  </td>

</div>

Thanks to everyone:)

    
asked by E.Rawrdríguez.Ophanim 14.09.2017 в 20:02
source

3 answers

1

Happy afternoon as you use razor to do the foreach you can also do an if to verify before crossing if your object is null

@model PCotiza_compras.Models.ReqCatDep

@{
    ViewBag.Title = "Kyo";
}


<div class="panel-group" id="accordion">
  <td>
      @if(Model != null && Model.Cat != null)
      {
        @foreach (var item in Model.Cat)
        {
            <tr>
                @item.Name
            </tr>
            <tr>
                @item.Description
            </tr>
        }
      }     
  </td>

</div>

in this way you will not have that error but you must fill the list in the controller

    
answered by 14.09.2017 / 20:07
source
2

Brother, I see that you have several problems, we are going to solve them:

[Authorize]
public ActionResult Kyo( )
{
    //Aqui te hace falta tu modelo.
    var modelo = llamas a tu base de datos, a la tabla que deseas.
    modelo.cat = lista de elementos
    return View(modelo);
}

Check this code: link has a simple 3 layer project + database. The YouTube video explained in detail how ASPnet MVC works.

    
answered by 14.09.2017 в 20:30
1

You are not passing the model to your eyes, you should do something like this:

    [Authorize]
    public ActionResult Kyo( )
    {
          // Debes crear la logica para llenar el modelo y pasarlo a la vista
          var model = LlenarReqCatDep();


          return View(model);
    }

Obvious that for your code to be of the best quality, you must validate that the data required by the view are in the model.

    
answered by 14.09.2017 в 20:34