Problems with ASP.NET MVC

Asked

Viewed 137 times

-1

Has anyone ever had a mistake like this?inserir a descrição da imagem aqui

Code of the View Index:

@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; }
    }
}
  • 1

    Enter your code.

  • put your index.cshtml code

  • Model code, controller

  • I’m using DDD, Automapper and Ninject architecture for dependency injection

  • 1

    "I’m using DDD, Automapper and Ninject architecture for dependency injection". -1.

2 answers

2

UsuarioViewModel is not an enumeration (does not implement IEnumerable), therefore, it cannot be iterated (it cannot be used in a foreach).

Your Action Index returns nothing. Hardly this code will work.

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

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

But I’m telling you, if _usuarioApp envelope anything from the Entity Framework, this is bad practice. See why here.

Your View possibly will have to change as well, 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 bank, precisely because it is Viewmodel, and not Model.

0

Compiler Error CS1579

The foreach statement cannot 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 instruction, the collection must meet the following requirements: It must be an interface, a class or a structure. It should include a public Getenumerator method that returns a type. The return type must contain a public property called Current, and a public method called Movenext. For more information, see How to access a collection class with foreach (Programming Guide in C#).

Example In this example, foreach cannot 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);
      }
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.