Problems with ASP.NET MVC

-1

Has anyone ever had an error like this?

View Index Code:

@model SPTC.NIE.SPG.Application.ViewModels.UsuarioViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.TipoUsuarioViewModel.Descricao)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Nome)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Ativo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.DataCadastro)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.TipoUsuarioViewModel.Descricao)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Nome)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Ativo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DataCadastro)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.UsuarioId }) |
            @Html.ActionLink("Details", "Details", new { id=item.UsuarioId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.UsuarioId })
        </td>
    </tr>
}

</table>

Controller:

using System.Web.Mvc;
using SPTC.NIE.SPG.Application.ViewModels;
using System.Threading.Tasks;
using SPTC.NIE.SPG.Application.Interfaces;

namespace SPTC.NIE.ProtocoloGeral.MVC.Controllers
{
    public class UsuariosController : Controller
    {
        private readonly IUsuarioAppService _usuarioApp;
        private readonly ITipoUsuarioAppService _tipoUsuarioApp;
        public UsuariosController()
        {

        }
        public UsuariosController(IUsuarioAppService usuarioApp, ITipoUsuarioAppService tipoUsuarioApp)
        {
            _usuarioApp = usuarioApp;
            _tipoUsuarioApp = tipoUsuarioApp;
        }
        // GET: Usuarios
        public ActionResult Index()
        {
            return View();
        }

        // GET: Usuarios/Details/5
        public ActionResult Details(int id)
        {
            var usuarioViewModel = _usuarioApp.GetById(id);

            if (usuarioViewModel == null)
            {
                return HttpNotFound();
            }
            return View(usuarioViewModel);
        }

        // GET: Usuarios/Create
        public async Task<ActionResult> Create()
        {
            ViewBag.TipoUsuarioId = new SelectList(await _tipoUsuarioApp.GetAll(), "TipoUsuarioId", "Descricao");
            return View();
        }

        // POST: Usuarios/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(UsuarioViewModel usuario)
        {
            if (ModelState.IsValid)
            {
                ViewBag.TipoUsuarioId = new SelectList(await _tipoUsuarioApp.GetAll(), "TipoUsuarioId", "Descricao");
                _usuarioApp.Add(usuario);
                return RedirectToAction("Index");
            }
            return View(usuario);
        }

        // GET: Usuarios/Edit/5
        public async Task<ActionResult> Edit(int UsuarioId)
        {
            var tipo = await _tipoUsuarioApp.GetAll();
            var usuario = _usuarioApp.GetById(UsuarioId);
            if(usuario == null)
            {
                return HttpNotFound();
            }

            ViewBag.TipoUsuarioId = new SelectList(tipo, "TipoUsuarioId", "Descricao");
            return View(usuario);
        }

        // POST: Usuarios/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(UsuarioViewModel usuario)
        {
            if (ModelState.IsValid)
            {
                _usuarioApp.Update(usuario);
                return RedirectToAction("Index");
            }
            //ViewBag.TipoUsuarioId = new SelectList(db.TipoUsuarioViewModels, "TipoUsuarioId", "Descricao", usuario.TipoUsuarioId);
            return View(usuario);
        }

        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing)
        //    {
        //        _usuarioApp.Dispose();
        //    }
        //    base.Dispose(disposing);
        //}
    }
}

ViewModel class:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace SPTC.NIE.SPG.Application.ViewModels
{
    public class UsuarioViewModel
    {
        [Key]
        public int UsuarioId { get; set; }
        public int TipoUsuarioId { get; set; }

        [Display(Name ="Nome do Usuário")]
        [Required(ErrorMessage ="O nome é obrigatório.")]
        [MaxLength(60, ErrorMessage ="O Nome do Usuário poderá ter no máximo 60 caracteres.")]
        public string Nome { get; set; }

        [Display(Name = "E-mail")]
        [Required(ErrorMessage = "O E-mail é obrigatório.")]
        [MaxLength(80, ErrorMessage = "O E-mail poderá ter no máximo 80 caracteres.")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }

        public bool Ativo { get; set; }

        [Display(Name = "Data de Cadasatro")]
        public DateTime DataCadastro { get; set; }

        public virtual TipoUsuarioViewModel TipoUsuarioViewModel { get; set; }

        public virtual ICollection<ExpedienteUsuarioViewModel> ExpedienteUsuariosViewModel { get; set; }
    }
}
    
asked by anonymous 04.11.2016 / 17:36

2 answers

2

UsuarioViewModel is not an enumeration (it does not implement IEnumerable ), so it can not be iterated (can not be used in foreach ).

Your Action Index does not return anything. Hardly this code will work.

If the idea is to bring all users, I think the idea is this:

public ActionResult Index()
{
    var usuarios = _usuarioApp.GetAll();
    return View(usuarios);
}

But what's more, if _usuarioApp envelopes anything in the Entity Framework, this is a bad practice. See why here .

Your View will probably have to change too, to:

@model IEnumerable<SPTC.NIE.SPG.Application.Models.Usuario>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.TipoUsuarioViewModel.Descricao)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Nome)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Ativo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.DataCadastro)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.TipoUsuarioViewModel.Descricao)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Nome)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Ativo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DataCadastro)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.UsuarioId }) |
            @Html.ActionLink("Details", "Details", new { id=item.UsuarioId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.UsuarioId })
        </td>
    </tr>
}

</table>

This is because UsuarioViewModel is not persisted in database, precisely because it is ViewModel , not Model .

    
04.11.2016 / 17:55
0

Compiler Error CS1579

The foreach statement can not operate with variables of type "- 1" as "type 2" does not contain a public definition of and the message " To iterate through a collection using the foreach statement, the collection must meet the following requirements: It must be an interface, a class, or a structure. Must include a public GetEnumerator method that returns a type. The return type must contain a public property called Current, and a public method named MoveNext. For more information, see How to Access a Collection Class with foreach (C # Programming Guide).

Example In this example, foreach can not iterate through the collection because there is no publicGetEnumerator method in MyCollection.

// CS1579.cs
using System;
public class MyCollection 
{
   int[] items;
   public MyCollection() 
   {
      items = new int[5] {12, 44, 33, 2, 50};
   }

   // Delete the following line to resolve.
   MyEnumerator GetEnumerator()

   // Uncomment the following line to resolve:
   // public MyEnumerator GetEnumerator() 
   {
      return new MyEnumerator(this);
   }

   // Declare the enumerator class:
   public class MyEnumerator 
   {
      int nIndex;
      MyCollection collection;
      public MyEnumerator(MyCollection coll) 
      {
         collection = coll;
         nIndex = -1;
      }

      public bool MoveNext() 
      {
         nIndex++;
         return(nIndex < collection.items.GetLength(0));
      }

      public int Current 
      {
         get 
         {
            return(collection.items[nIndex]);
         }
      }
   }

   public static void Main() 
   {
      MyCollection col = new MyCollection();
      Console.WriteLine("Values in the collection are:");
      foreach (int i in col)   // CS1579
      {
         Console.WriteLine(i);
      }
   }
}
    
04.11.2016 / 17:51