Skip to content

Instantly share code, notes, and snippets.

@cleytonferrari
Created March 2, 2013 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cleytonferrari/5070711 to your computer and use it in GitHub Desktop.
Save cleytonferrari/5070711 to your computer and use it in GitHub Desktop.
Exemplo de uso de ViewModel
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication6.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var noticiaVM = new NoticiaViewModel();
//noticiaVM.Noticia = CarregaNoticia.FirstOrDefault();
//noticiaVM.Comentarios = CarregaComentarios.Where(x => x.NoticiaId = noticiaVM.Noticia.NoticiaId).ToList();
return View(noticiaVM);
}
}
//CRIE AS CLASSES NO MESMO ARQUIVO DO CONTROLLER SO PRA FICAR MAIS FACIL ENTENDER
public class NoticiaViewModel
{
public NoticiaViewModel()
{
Noticia = new Noticia();
Comentarios = new Collection<Comentarios>();
}
public Noticia Noticia { get; set; }
public ICollection<Comentarios> Comentarios { get; set; }
}
public class Noticia
{
public int NoticiaId { get; set; }
public string Titulo { get; set; }
}
public class Comentarios
{
public int ComentarioId { get; set; }
public string Comentario { get; set; }
public int NoticiaId { get; set; }
}
}
@model MvcApplication6.Controllers.NoticiaViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<fieldset>
<legend>NoticiaViewModel</legend>
@Model.Noticia.Titulo
@foreach (var comentario in Model.Comentarios)
{
<p>@comentario.Comentario</p>
}
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
@Html.ActionLink("Back to List", "Index")
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment