How to get specific information from Tolistasync

Asked

Viewed 108 times

-1

I would like to create a system that prints on the Index page each Post equal to the image below inserir a descrição da imagem aqui

And for this I created a method that searches the last 3 posts, however, I do not know how to print in the view, because when I use foreach it creates several times the front end. How can I Print this data in a way that I can access a specific position of the array that it returned to me in Tolistasync?

Controller:

using Blog.Data;
using Blog.Models;
using Blog.Services;
using Blog.Services.Exceptions;
using Blog.Services.Exceptions.Exceptions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using Blog.Areas.Identity.Data;

namespace Blog.Controllers
{
    public class PostagemsController : Controller
    {
        private readonly PostagemService _postagemService;

        private readonly BlogContext _context;

        private UserManager<BlogUser> _userManager;

        public PostagemsController(PostagemService postagemService, BlogContext context, UserManager<BlogUser> userManager)
        {
            _postagemService = postagemService;
            _context = context;
            _userManager = userManager;

        }


        [Authorize]
        public async Task<IActionResult> Index()
        {

            var list = await _postagemService.FindAllAsync();
            return View(list);
        }


        // GET: Postagems


        [Authorize]
        public IActionResult Create()
        {

            ViewData["AssuntoSelect"] = new SelectList(_context.Assunto, "Id", "Nome");
            ViewData["UserSelect"] = new SelectList(_context.BlogUser, "Id", "Email");

            return View();

        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Postagem Postagem)
        {
            var user = await _userManager.GetUserAsync(User);
            var id = user.Id;

            Postagem.Status = "1";
            Postagem.DataPostagem = DateTime.Now;
            Postagem.Likes = 0;
            Postagem.BlogUserId = id;
            Postagem.Visualizacoes = 0;





            if (!ModelState.IsValid)
            {
                return View();
            }

            await _postagemService.InsertAsync(Postagem);
            return RedirectToAction(nameof(Index));
        }

        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not provided" });
            }

            var obj = await _postagemService.FindByIdAsync(id.Value);
            if (obj == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not found" });

            }

            return View(obj);
        }
        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _postagemService.RemoveAsync(id);
                return RedirectToAction(nameof(Index));
            }
            catch (IntegrityException e)
            {
                return RedirectToAction(nameof(Error), new { message = e.Message });
            }
        }

        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not provided" });
            }

            var obj = await _postagemService.FindByIdAsync(id.Value);
            if (obj == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not found" });

            }

            return View(obj);

        }

        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not provided" });
            }

            var obj = await _postagemService.FindByIdAsync(id.Value);
            if (obj == null)
            {
                return RedirectToAction(nameof(Error), new { message = "Id not found" });
            }


            return View();
        }

        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public async Task<IActionResult> Edit(int id, Postagem Postagem)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }
            if (id != Postagem.Id)
            {
                return RedirectToAction(nameof(Error), new { message = "Id mismatch" });
            }
            try
            {
                await _postagemService.UpdateAsync(Postagem);
                return RedirectToAction(nameof(Index));
            }
            catch (NotFoundException e)
            {
                return RedirectToAction(nameof(Error), new { message = e.Message });
            }
            catch (DbConcurrencyException e)
            {
                return RedirectToAction(nameof(Error), new { message = e.Message });
            }
        }

        public IActionResult Error(string message)
        {
            var viewModel = new ErrorViewModel
            {

                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
            };
            return View();

        }


        /*
        public IActionResult Create()
        {
            ViewData["PostagemId"] = new SelectList(_context.Postagem, "Id", "Nome");
            ViewData["PostagemId1"] = new SelectList(_context1.BlogUser,"Id","Email");
            return View();
        }
        */


    }
}

Services


using Blog.Data;
using Blog.Models;
using Blog.Services.Exceptions;
using Blog.Services.Exceptions.Exceptions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;

namespace Blog.Services
{
    public class PostagemService
    {

        private readonly BlogContext _context;

        public PostagemService(BlogContext context)
        {
            _context = context;


        }

        public async Task<List<Postagem>> FindAllAsync()
        {
            return  await _context.Postagem.Include(obj => obj.Assunto).ToListAsync();
        }

        public async Task InsertAsync(Postagem obj)
        {

            _context.Add(obj);
            await _context.SaveChangesAsync();
        }

        public async Task<Postagem> FindByIdAsync(int id)
        {
            return await _context.Postagem.Include(obj => obj.Assunto).FirstOrDefaultAsync(obj => obj.Id == id);
        }

        public async Task RemoveAsync(int id)
        {
            try
            {
                var obj = await _context.Postagem.FindAsync(id);
                _context.Postagem.Remove(obj);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException e)
            {
                throw new IntegrityException(e.Message);
            }
        }

        public async Task UpdateAsync(Postagem obj)
        {
            bool hasAny = await _context.Postagem.AnyAsync(x => x.Id == obj.Id);
            if (!hasAny)
            {
                throw new NotFoundException("Id not Found");
            }

            try
            {
                _context.Update(obj);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException e)
            {
                throw new DbConcurrencyException(e.Message);
            }
        }


        public async Task<List<Postagem>> EncontrarUltimas3()
        {
            var result = _context.Postagem.Include(obj => obj.Assunto).OrderByDescending(obj => obj.DataPostagem).Take(3).ToListAsync();
            return await result;
        }

        //var result = _context.Postagem.Where(p => p.Status == "2").Include(obj => obj.Assunto).ToListAsync();
        //return await result;
        //return  await _context.Postagem.Include(obj => obj.Assunto).Where(p => p.Status == "1").OrderBy(p => p.DataPostagem).Take(4).ToListAsync();

    }
}

Model:

using Blog.Areas.Identity.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace Blog.Models
{
    public class Postagem
    {


        //Atributos

        public int Id { get; set; }


        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public DateTime DataPostagem { get; set; }


        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public DateTime DataAtualizacao { get; set; }

        [Required(ErrorMessage = "{0} required")]
        public string Titulo { get; set; }


        public string Descricao { get; set; }

        [Required(ErrorMessage = "{0} required")]
        [DataType(DataType.Text)]
        public string Texto { get; set; }


        public string Status { get; set; }

        public int Likes { get; set; }
        public int Visualizacoes { get; set; }
        public string ImagemInicial { get; set; }

        //Chaves Estrangeiras
        public Assunto Assunto { get; set; }
        public BlogUser BlogUser { get; set; }
        public int AssuntoId { get; set; }
        public string BlogUserId { get; set; }

        public ICollection<Comentario> Comentarios { get; set; } = new List<Comentario>();


        public Postagem()
        {


        }

        public Postagem(int id, DateTime dataPostagem, DateTime dataAtualizacao, string titulo, string descricao, string texto, string status, Assunto assunto, BlogUser blogUser)
        {

            Id = id;
            DataPostagem = dataPostagem;
            DataAtualizacao = dataAtualizacao;
            Titulo = titulo;
            Descricao = descricao;
            Texto = texto;
            Status = status;
            Assunto = assunto;
            BlogUser = blogUser;

        }

    }
}

If you have any other way to do it, please leave your suggestion.

1 answer

0

I managed to solve.

For this I created a Viewmodel To Store each collection I was passing, in the controller I created an object to store the result of each query and then in the view referenced my Viewmodel. The code of everything was like this:

View Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Blog.Models;

namespace Blog.ViewModel
{
    public class ExibirPostagemsViewModel
    {

        public IEnumerable<Postagem> CollectionA { get; set; }
        public IEnumerable<Postagem> CollectionB { get; set; }
        public IEnumerable<Postagem> CollectionC { get; set; }
    }
}

Controller:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Blog.Models;
using Blog.Services;
using Blog.ViewModel;

namespace Blog.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private readonly PostagemService _postagemService;

        public HomeController(ILogger<HomeController> logger, PostagemService postagemService)
        {
            _postagemService = postagemService;
            _logger = logger;
        }

        public async Task<IActionResult> Index()
        {
            var model = new ExibirPostagemsViewModel()
            {


                CollectionA = await _postagemService.EncontrarPrimeira(),
            CollectionB = await _postagemService.EncontrarSegunda(),
                CollectionC = await _postagemService.EncontrarTerceira(),
            };

            return View(model);

        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

View:

@model Blog.ViewModel.ExibirPostagemsViewModel
@{


    ViewData["Title"] = "Home Page";


}

<div class="section">
    <!-- container -->
    <div class="container">


        <!-- row -->
        <div id="hot-post" class="row hot-post">

            @foreach (var item in Model.CollectionA)
            {



                <div class="col-md-8 hot-post-left">
                    <!-- post -->
                    <div class="post post-thumb">
                        <a class="post-img" href="blog-post.html"><img src="@Html.DisplayFor(modelItem => item.ImagemInicial)" alt=""></a>

                        <div class="post-body">
                            <div class="post-category">
                                <a href="category.html">Lifestyle</a>
                            </div>
                            <h3 class="post-title title-lg"><a href="blog-post.html">Postea senserit id eos, vivendo periculis ei qui</a></h3>
                            <ul class="post-meta">
                                <li><a href="author.html">John Doe</a></li>
                                <li>20 April 2018</li>
                            </ul>
                        </div>
                    </div>
                    <!-- /post -->
                </div>
            }
        <div class="col-md-4 hot-post-right">
            @foreach (var item in Model.CollectionB)
            {

                <!-- post -->
                <div class="post post-thumb">
                    <a class="post-img" href="blog-post.html"><img src="@Html.DisplayFor(modelItem => item.ImagemInicial)" alt=""></a>
                    <div class="post-body">
                        <div class="post-category">
                            <a href="category.html">Lifestyle</a>
                        </div>
                        <h3 class="post-title"><a href="blog-post.html">Sed ut perspiciatis, unde omnis iste natus error sit</a></h3>
                        <ul class="post-meta">
                            <li><a href="author.html">John Doe</a></li>
                            <li>20 April 2018</li>
                        </ul>
                    </div>
                </div>
            }

            @foreach (var item in Model.CollectionC)
            {
                <!-- /post -->
                <!-- post -->
                <div class="post post-thumb">
                    <a class="post-img" href="blog-post.html"><img src="@Html.DisplayFor(modelItem => item.ImagemInicial)" alt=""></a>
                    <div class="post-body">
                        <div class="post-category">
                            <a href="category.html">Fashion</a>
                            <a href="category.html">Lifestyle</a>
                        </div>
                        <h3 class="post-title"><a href="blog-post.html">Mel ut impetus suscipit tincidunt. Cum id ullum laboramus persequeris.</a></h3>
                        <ul class="post-meta">
                            <li><a href="author.html">John Doe</a></li>
                            <li>20 April 2018</li>
                        </ul>
                    </div>
                </div>
            }
                <!-- /post -->
            </div>
        </div>

        <!-- /row -->



    </div>
    <!-- /container -->
</div>

What I was able to conclude is that if you want to pass more than one value to the View, be it fixed or a bank select, the best way is to create a Viewmodel for this.

Browser other questions tagged

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