1
Hello. I’m doing a project for a music player. In the Playlist register, I would like the songs to appear in checkbox so I can mark the desired ones and save in the database.
This is my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XMusic.MVC.Models;
using XMusic.MVC.Persistencia;
namespace XMusic.MVC.Controllers
{
public class PlayListController : Controller
{
private PersistenciaPlayList persistenciaPlayList;
private ContextoEF contextoEF;
private PersistenciaUsuario persistenciaUsuario;
private PersistenciaMusica persistenciaMusica;
public PlayListController()
{
persistenciaPlayList = new PersistenciaPlayList();
persistenciaMusica = new PersistenciaMusica();
contextoEF = new ContextoEF();
persistenciaUsuario = new Persistencia.PersistenciaUsuario();
ViewData["usuarios"] = persistenciaUsuario.ObterTodos();
ViewData["musicas"] = persistenciaMusica.ObterTodas();
}
public ActionResult Index()
{
var playlists = persistenciaPlayList.ObterTodos();
return View(playlists);
}
[HttpGet]
public ActionResult Adicionar()
{
return View();
}
[HttpPost]
public ActionResult Adicionar(PlayList playlist)
{
var msgAlerta = string.Empty;
var tipoAlerta = string.Empty;
try
{
if (!ModelState.IsValid)
throw new Exception();
persistenciaPlayList.Adicionar(playlist);
ModelState.Clear();
msgAlerta = "PlayList cadastrada com sucesso";
tipoAlerta = "alert-success";
}
catch (Exception e)
{
msgAlerta = "Ocorreu um erro ao cadastrar a PlayList" + e;
tipoAlerta = "alert-danger";
}
TempData.Add("MsgAlerta", msgAlerta);
TempData.Add("TipoAlerta", tipoAlerta);
return View();
}
[HttpGet]
public ViewResult Alterar(int playlistId)
{
var playlist = persistenciaPlayList.Obter(playlistId);
return View(playlist);
}
[HttpPost]
public ActionResult Alterar(PlayList playlist)
{
var msgAlerta = string.Empty;
var tipoAlerta = string.Empty;
var alterado = false;
try
{
if (!ModelState.IsValid)
throw new Exception();
alterado = persistenciaPlayList.Alterar(playlist);
if (alterado)
{
msgAlerta = "PlayList alterada com sucesso";
tipoAlerta = "alert-success";
}
else
{
msgAlerta = "Ocorreu um erro ao alterar a PlayList";
tipoAlerta = "alert-danger";
}
}
catch (Exception e)
{
alterado = false;
msgAlerta = "Ocorreu um erro ao alterar a PlayList: " + e;
tipoAlerta = "alert-danger";
}
TempData.Add("MsgAlerta", msgAlerta);
TempData.Add("TipoAlerta", tipoAlerta);
if (alterado)
return RedirectToAction("Index");
else
return View();
}
[HttpGet]
public JsonResult ObterUsuarios()
{
var msg = string.Empty;
var listaUsuarios = persistenciaUsuario.ObterTodos();
if (!listaUsuarios.Any())
{
msg = "Nenhum usuário encontrado";
}
var usuarios = from u in listaUsuarios
select new { UsuarioId = u.UsuarioId, Nome = u.Nome };
return Json(new { ret = usuarios, mensagem = msg },
JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult ObterMusicas()
{
var msg = string.Empty;
var listaMusicas = persistenciaMusica.ObterTodas();
if (!listaMusicas.Any())
{
msg = "Nenhum música encontrada";
}
var musicas = from m in listaMusicas
select new { MusicaId = m.MusicaId, Titulo = m.Titulo };
return Json(new { ret = musicas, mensagem = msg },
JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult ObterTodos()
{
var msg = string.Empty;
var listaPlayList = persistenciaPlayList.ObterTodos().ToList();
if (!listaPlayList.Any())
{
msg = "Nenhuma PlayList encontrada";
}
var playlist = from p in listaPlayList
select new { PlayListId = p.PlayListId, Titulo = p.Titulo };
return Json(new { ret = playlist, mensagem = msg },
JsonRequestBehavior.AllowGet);
}
}
}
This is the persistent Playlist:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using XMusic.MVC.Models;
namespace XMusic.MVC.Persistencia
{
public class PersistenciaPlayList
{
private ContextoEF _contexto = new ContextoEF();
public PlayList Adicionar(PlayList playlist)
{
_contexto.Playlists.Add(playlist);
_contexto.SaveChanges();
return playlist;
}
public IEnumerable<PlayList> ObterTodos()
{
return _contexto.Playlists.ToList();
}
public PlayList Obter(int id)
{
try
{
return _contexto.Playlists.FirstOrDefault(p => p.PlayListId == id);
}
catch
{
throw;
}
}
public bool Alterar(PlayList playlist)
{
try
{
var p = _contexto.Playlists.Find(playlist.PlayListId);
if (p != null)
{
p.Titulo = playlist.Titulo;
p.UsuarioId = playlist.UsuarioId;
p.Musicas = playlist.Musicas;
_contexto.Entry(p).State = EntityState.Modified;
_contexto.SaveChanges();
return true;
}
else
return false;
}
catch
{
throw;
}
}
public PlayList Remover(int id)
{
try
{
var p = _contexto.Playlists.Find(id);
_contexto.Playlists.Remove(p);
_contexto.SaveChanges();
return p;
}
catch
{
return null;
}
}
}
}
And here where I am showing the data. I would like the music data, to be shown in checkbox:
@model XMusic.MVC.Models.PlayList
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Titulo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Titulo, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Titulo, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.UsuarioId, "Usuário", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList(
"UsuarioId",
new SelectList(
(IEnumerable<XMusic.MVC.Models.Usuario>)ViewData["usuarios"],
"UsuarioId",
"Nome"),
htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.UsuarioId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Musicas, "Músicas", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList(
"MusicaId",
new SelectList(
(IEnumerable<XMusic.MVC.Models.Musica>)ViewData["musicas"],
"MusicaId",
"Titulo"),
htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Musicas, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Salvar" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Lista de PlayLists", "Index")
</div>