-1
I would like to create a system that prints on the Index page each Post equal to the image below
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.