Asp.net MVC #RenderPage with Data - c#

I have controller
public class NewsController : Controller
{
private SchoolDbContext db = new SchoolDbContext();
//
// GET: /News/
public ActionResult Index()
{
return View(db.News.ToList());
}
//
// GET: /News/Details/5
public ActionResult Details(int id = 0)
{
News news = db.News.Find(id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
//
// GET: /News/Create
public ActionResult Create()
{
return View();
}
//
// POST: /News/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(News news)
{
if (ModelState.IsValid)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
string path2 = Path.GetRandomFileName();
fileName = path2 + fileName;
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
news.Image = fileName;
file.SaveAs(path);
}
db.News.Add(news);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(news);
}
//
// GET: /News/Edit/5
public ActionResult Edit(int id = 0)
{
News news = db.News.Find(id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
//
// POST: /News/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(News news)
{
if (ModelState.IsValid)
{
db.Entry(news).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(news);
}
//
// GET: /News/Delete/5
public ActionResult Delete(int id = 0)
{
News news = db.News.Find(id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
//
// POST: /News/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
News news = db.News.Find(id);
db.News.Remove(news);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
I have a Model
public class News
{
[Key]
public int newsID { get; set; }
[Required]
public string newsName { get; set; }
[Required]
public string newsDescription { get; set; }
public string Image { get; set; }
}
and a simple view
<div class="grid">
#foreach (var item in Model)
{
<div class="holder_content">
<section class="group1">
<h3>#Html.DisplayFor(modelItem => item.newsName)</h3>
<p class="desc">#Html.DisplayFor(modelItem => item.newsDescription)</p>
<a class="photo_hover3" href="#"><img src="~/Uploads/#Html.DisplayFor(modelItem => item.Image)" width="240" height="214" alt=""></a>
<div class="forbutton">
#Html.ActionLink("სრულად ", "Details", new { id = item.newsID }, new { #class = "button" })
</div>
#{ if (User.Identity.IsAuthenticated)
{
#Html.ActionLink("Edit ", "Edit", new { id = item.newsID })
#Html.ActionLink("Delete", "Delete", new { id = item.newsID })
}
}
</section>
}
I want to display this data in another page, where I have this code
#RenderPage("~/Views/News/Index.cshtml")
but web page goes on runtime error, with null pointer exception on foreach tag
have you any solution with this error? sorry for my english. Hope you understand

Please use the partial view rendering.
Note main thing you have to mention the namespace in the view page
Like : #model YourApplicationName.Models.exampleClassName
and then render the page as partial view.
#Html.Partial("partialViewName", new exampleClassName())
or other wise pass the model which you have denoted as namespace in the Partialview like below
#Html.Partial("partialViewName", #Modle.exampleClassName)
or
#Html.Partial("partialViewName", #Modle)

Related

How to retrieve data of nested class instance from parent class instance in ASP.NET Core?

I am trying to modeling a class at school, and I end up with something like this:
public class Class
{
public int ID { get; set; }
public int Grade { get; set; }
public Teacher ClassTeacher { get; set; }
}
This is the Teacher class:
public class Teacher
{
public int ID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
public DateTime Birthday { get; set; }
}
When I use scaffolding, migrate and update the database, this is the structure Entity Framework built for me:
dbo.Class:
ID: int
ClassTeacherID: int
Grade: int
dbo.Teacher:
ID: int
Birthday: datetime2(7)
FirstName: nvarchar(MAX)
LastName: nvarchar(MAX)
I want to display the Teacher's FirstName in Views\Classes\Details.cshtml, but the Model.ClassTeacher is null, even after I created a Teacher instance in the database and set ClassTeacherID to the newly created Teacher's ID.
Looking for your helps.
EDIT
ClassesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Models
{
public class ClassesController : Controller
{
private readonly WebApplication1Context _context;
public ClassesController(WebApplication1Context context)
{
_context = context;
}
// GET: Classes
public async Task<IActionResult> Index()
{
return View(await _context.Class.ToListAsync());
}
// GET: Classes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var #class = await _context.Class
.SingleOrDefaultAsync(m => m.ID == id);
if (#class == null)
{
return NotFound();
}
return View(#class);
}
// GET: Classes/Create
public IActionResult Create()
{
return View();
}
// POST: Classes/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<IActionResult> Create([Bind("ID,Grade")] Class #class)
{
if (ModelState.IsValid)
{
_context.Add(#class);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(#class);
}
// GET: Classes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var #class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
if (#class == null)
{
return NotFound();
}
return View(#class);
}
// POST: Classes/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 async Task<IActionResult> Edit(int id, [Bind("ID,Grade")] Class #class)
{
if (id != #class.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(#class);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ClassExists(#class.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(#class);
}
// GET: Classes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var #class = await _context.Class
.SingleOrDefaultAsync(m => m.ID == id);
if (#class == null)
{
return NotFound();
}
return View(#class);
}
// POST: Classes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var #class = await _context.Class.SingleOrDefaultAsync(m => m.ID == id);
_context.Class.Remove(#class);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool ClassExists(int id)
{
return _context.Class.Any(e => e.ID == id);
}
}
}
TeachersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
namespace WebApplication1.Models
{
public class TeachersController : Controller
{
private readonly WebApplication1Context _context;
public TeachersController(WebApplication1Context context)
{
_context = context;
}
// GET: Teachers
public async Task<IActionResult> Index()
{
return View(await _context.Teacher.ToListAsync());
}
// GET: Teachers/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher
.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// GET: Teachers/Create
public IActionResult Create()
{
return View();
}
// POST: Teachers/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<IActionResult> Create([Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
{
if (ModelState.IsValid)
{
_context.Add(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(teacher);
}
// GET: Teachers/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// POST: Teachers/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 async Task<IActionResult> Edit(int id, [Bind("ID,FirstName,LastName,Birthday")] Teacher teacher)
{
if (id != teacher.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(teacher);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TeacherExists(teacher.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(teacher);
}
// GET: Teachers/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var teacher = await _context.Teacher
.SingleOrDefaultAsync(m => m.ID == id);
if (teacher == null)
{
return NotFound();
}
return View(teacher);
}
// POST: Teachers/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var teacher = await _context.Teacher.SingleOrDefaultAsync(m => m.ID == id);
_context.Teacher.Remove(teacher);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool TeacherExists(int id)
{
return _context.Teacher.Any(e => e.ID == id);
}
}
}
I know it's been a while since the question has been written, but you should try to Include the object reference you want.
var #class = await _context.Class.Include("Teacher")
.SingleOrDefaultAsync(m => m.ID == id);
Include will get the dependent object and put it back in your Class model.
You can chain the Include directives if you have different referenced objects.
Note : You will have to add :
using Microsoft.EntityFrameworkCore;
on top of your code to allow Include to work.

Many to many relationship ASP.NET MVC and ASP.NET WEB API

So, i have two projects, WebAPI and Client. The Client uses the database of the WebAPI project, and does not have it's own. Everything is working fine in one-to-one relationships and one-to-many relationships. However, i now need to figure out how to make it work with many-to-many relationships. I'll be posting my code, so, to better explain myself i will write with the real class names as you will be able to understand due to the code i will post further.
In my WebApi.Models i have two classes, PlanoManutencao and Ativo. This is a many-to-many relationship. Here are the classes:
public class PlanoManutencao
{
public PlanoManutencao()
{
Ativos = new List<Ativo>();
Operacoes = new List<Operacao>();
}
public int ID { get; set; }
public string Nome { get; set; }
public string Observacoes { get; set; }
public bool Permanente { get; set; }
public DateTime DataCriacao { get; set; }
public virtual ICollection<Ativo> Ativos { get; set; }
public virtual ICollection<Operacao> Operacoes { get; set; }
}
public class Ativo
{
public Ativo()
{
PlanosManutencao = new List<PlanoManutencao>();
}
public int ID { get; set; }
public string Nome { get; set; }
public string Descricao { get; set; }
public virtual ICollection<PlanoManutencao> PlanosManutencao { get; set; }
}
Now, in my WebAPI i'm using repositories, as follows:
public class PlanosManutencaoRepository : IPlanosManutencaoRepository
{
public ApplicationDbContext context;
public PlanosManutencaoRepository()
{
context = new ApplicationDbContext();
}
public PlanoManutencao Create(PlanoManutencao planoManutencao)
{
context.PlanosManutencao.Add(planoManutencao);
context.SaveChanges();
return planoManutencao;
}
public bool Delete(int id)
{
var planoManutencao = context.PlanosManutencao.Find(id);
if (planoManutencao != null)
{
context.PlanosManutencao.Remove(planoManutencao);
context.SaveChanges();
return true;
}
else return false;
}
public List<PlanoManutencao> GetData()
{
var planosManutencao = context.PlanosManutencao.ToList();
return planosManutencao;
}
public List<PlanoManutencao> GetData(DateTime data)
{
var planosManutencao = context.PlanosManutencao.Where(f => f.DataCriacao == data);
return planosManutencao.ToList();
}
public PlanoManutencao GetDataById(int id)
{
return context.PlanosManutencao.Find(id);
}
public bool Update(int id, PlanoManutencao planoManutencao)
{
var planoManutencaoAux = context.PlanosManutencao.Find(id);
if (planoManutencao != null)
{
planoManutencaoAux.DataCriacao = planoManutencao.DataCriacao;
context.SaveChanges();
return true;
}
else return false;
}
}
public class AtivosRepository : IAtivosRepository
{
public ApplicationDbContext context;
public AtivosRepository()
{
context = new ApplicationDbContext();
}
public Ativo Create(Ativo ativo)
{
context.Ativos.Add(ativo);
context.SaveChanges();
return ativo;
}
public bool Delete(int id)
{
var ativo = context.Ativos.Find(id);
if (ativo != null)
{
context.Ativos.Remove(ativo);
context.SaveChanges();
return true;
}
else return false;
}
public List<Ativo> GetData()
{
var ativos = context.Ativos.ToList();
return ativos;
}
public List<Ativo> GetData(string descricao)
{
var ativos = context.Ativos.Where(f => f.Descricao == descricao);
return ativos.ToList();
}
public Ativo GetDataById(int id)
{
return context.Ativos.Find(id);
}
public bool Update(int id, Ativo ativo)
{
var ativoAux = context.Ativos.Find(id);
if (ativo != null)
{
ativoAux.Nome = ativo.Nome;
ativoAux.Descricao = ativo.Descricao;
context.SaveChanges();
return true;
}
else return false;
}
}
Now, for the controllers, i have:
public class PlanosManutencaoController : ApiController
{
//private ApplicationDbContext db = new ApplicationDbContext();
private IPlanosManutencaoRepository repoPM = new PlanosManutencaoRepository();
// GET: api/PlanosManutencao
public IQueryable<PlanoManutencao> GetPlanoManutencaos()
{
return repoPM.GetData().AsQueryable();
}
// GET: api/PlanosManutencao/5
[ResponseType(typeof(PlanoManutencao))]
public IHttpActionResult GetPlanoManutencao(int id)
{
PlanoManutencao planoManutencao = repoPM.GetDataById(id);
if (planoManutencao == null)
{
return NotFound();
}
return Ok(planoManutencao);
}
// PUT: api/PlanosManutencao/5
[ResponseType(typeof(void))]
public IHttpActionResult PutPlanoManutencao(int id, PlanoManutencao planoManutencao)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != planoManutencao.ID)
{
return BadRequest();
}
bool isSucess = repoPM.Update(id, planoManutencao);
if (!PlanoManutencaoExists(id))
{
return NotFound();
}
return Ok();
}
// POST: api/PlanosManutencao
[ResponseType(typeof(PlanoManutencao))]
public IHttpActionResult PostPlanoManutencao(PlanoManutencao planoManutencao)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (repoPM.Create(planoManutencao) == null)
{
return StatusCode(HttpStatusCode.BadRequest);
}
return CreatedAtRoute("DefaultApi", new { id = planoManutencao.ID }, planoManutencao);
}
// DELETE: api/PlanosManutencao/5
[ResponseType(typeof(PlanoManutencao))]
public IHttpActionResult DeletePlanoManutencao(int id)
{
PlanoManutencao planoManutencao = repoPM.GetDataById(id);
if (planoManutencao == null)
{
return NotFound();
}
bool isSuccess = repoPM.Delete(id);
if (!isSuccess)
{
return StatusCode(HttpStatusCode.BadRequest);
}
return Ok();
}
private bool PlanoManutencaoExists(int id)
{
return repoPM.GetDataById(id) == null ? false : true;
}
}
public class AtivosController : ApiController
{
//private ApplicationDbContext db = new ApplicationDbContext();
private IAtivosRepository repoA = new AtivosRepository();
// GET: api/Ativos
public IQueryable<Ativo> GetAtivoes()
{
return repoA.GetData().AsQueryable();
}
// GET: api/Ativos/5
[ResponseType(typeof(Ativo))]
public IHttpActionResult GetAtivo(int id)
{
Ativo ativo = repoA.GetDataById(id);
if (ativo == null)
{
return NotFound();
}
return Ok(ativo);
}
// PUT: api/Ativos/5
[ResponseType(typeof(void))]
public IHttpActionResult PutAtivo(int id, Ativo ativo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != ativo.ID)
{
return BadRequest();
}
bool isSucess = repoA.Update(id, ativo);
if (!AtivoExists(id))
{
return NotFound();
}
return Ok();
}
// POST: api/Ativos
[ResponseType(typeof(Ativo))]
public IHttpActionResult PostAtivo(Ativo ativo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (repoA.Create(ativo) == null)
{
return StatusCode(HttpStatusCode.BadRequest);
}
return CreatedAtRoute("DefaultApi", new { id = ativo.ID }, ativo);
}
// DELETE: api/Ativos/5
[ResponseType(typeof(Ativo))]
public IHttpActionResult DeleteAtivo(int id)
{
Ativo ativo = repoA.GetDataById(id);
if (ativo == null)
{
return NotFound();
}
bool isSuccess = repoA.Delete(id);
if (!isSuccess)
{
return StatusCode(HttpStatusCode.BadRequest);
}
return Ok();
}
private bool AtivoExists(int id)
{
return repoA.GetDataById(id) == null ? false : true;
}
}
Now, as for the Client project, i'm using ViewModels,Controllers and Views.
ViewModels:
public class PlanoManutencaoViewModel
{
public PlanoManutencaoViewModel()
{
Ativos = new List<AtivoViewModel>();
Operacoes = new List<OperacaoViewModel>();
}
public int ID { get; set; }
[Display(Name = "Name")]
public string Nome { get; set; }
[Display(Name = "Observations")]
public string Observacoes { get; set; }
[Display(Name = "Permanent")]
public bool Permanente { get; set; }
[Display(Name = "Created")]
public DateTime DataCriacao { get; set; }
[Display(Name = "Assets")]
public virtual ICollection<AtivoViewModel> Ativos { get; set; }
[Display(Name = "Tasks")]
public virtual ICollection<OperacaoViewModel> Operacoes { get; set; }
}
public class AtivoViewModel
{
public AtivoViewModel()
{
PlanosManutencao = new List<PlanoManutencaoViewModel>();
}
public int ID { get; set; }
[Display(Name = "Name")]
public string Nome { get; set; }
[Display(Name = "Description")]
public string Descricao { get; set; }
public ICollection<PlanoManutencaoViewModel> PlanosManutencao { get; set; }
}
The controllers are as follows:
public class PlanosManutencaoController : Controller
{
// GET: PlanosManutencao
public async Task<ActionResult> Index()
{
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/PlanosManutencao");
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var planosManutencao =
JsonConvert.DeserializeObject<IEnumerable<PlanoManutencaoViewModel>>(content);
return View(planosManutencao);
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
// GET: PlanosManutencao/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/PlanosManutencao/" + id);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var plano = JsonConvert.DeserializeObject<PlanoManutencaoViewModel>(content);
if (plano == null) return HttpNotFound();
return View(plano);
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
// GET: PlanosManutencao/Create
public ActionResult Create()
{
PopulateDropDownListForAtivos();
return View();
}
// POST: PlanosManutencao/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(PlanoManutencaoViewModel planoManutencao)
{
try
{
PopulateDropDownListForAtivos(planoManutencao.Ativos);
var client = WebApiHttpClient.GetClient();
string planoManutencaoJSON = JsonConvert.SerializeObject(planoManutencao);
HttpContent content = new StringContent(planoManutencaoJSON, System.Text.Encoding.Unicode, "application/json");
var response = await client.PostAsync("api/PlanosManutencao", content);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
catch
{
return Content("Ocorreu um erro.");
}
}
// GET: PlanosManutencao/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/PlanosManutencao/" + id);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var planoManutencao = JsonConvert.DeserializeObject<PlanoManutencaoViewModel>(content);
if (planoManutencao == null) return HttpNotFound();
return View(planoManutencao);
}
return Content("Ocorreu um erro: " + response.StatusCode);
}
// POST: PlanosManutencao/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 async Task<ActionResult> Edit(PlanoManutencaoViewModel planoManutencao)
{
try
{
var client = WebApiHttpClient.GetClient();
string planoManutencaoJSON = JsonConvert.SerializeObject(planoManutencao);
HttpContent content = new StringContent(planoManutencaoJSON, System.Text.Encoding.Unicode, "application/json");
var response =
await client.PutAsync("api/PlanosManutencao/" + planoManutencao.ID, content);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
catch
{
return Content("Ocorreu um erro.");
}
}
// GET: PlanosManutencao/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/PlanosManutencao/" + id);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var planoManutencao = JsonConvert.DeserializeObject<PlanoManutencaoViewModel>(content);
if (planoManutencao == null) return HttpNotFound();
return View(planoManutencao);
}
return Content("Ocorreu um erro: " + response.StatusCode);
}
// POST: PlanosManutencao/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
try
{
var client = WebApiHttpClient.GetClient();
var response = await client.DeleteAsync("api/PlanosManutencao/" + id);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
catch
{
return Content("Ocorreu um erro.");
}
}
private void PopulateDropDownListForAtivos(object ativos = null)
{
IEnumerable<AtivoViewModel> vm = null;
using (var client=WebApiHttpClient.GetClient())
{
HttpResponseMessage response = client.GetAsync("api/Ativos").Result;
if(response.IsSuccessStatusCode)
{
vm = response.Content.ReadAsAsync<IEnumerable<AtivoViewModel>>().Result;
}
}
var Ativos = vm.ToList().OrderBy(i => i.ID);
ViewBag.Ativos = new SelectList(Ativos, "ID", "Nome");
}
}
public class AtivosController : Controller
{
// GET: Ativos
public async Task<ActionResult> Index()
{
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/Ativos");
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var ativos =
JsonConvert.DeserializeObject<IEnumerable<AtivoViewModel>>(content);
return View(ativos);
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
// GET: Ativos/Details/5
public async Task<ActionResult> Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/Ativos/" + id);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var ativo = JsonConvert.DeserializeObject<AtivoViewModel>(content);
if (ativo == null) return HttpNotFound();
return View(ativo);
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
// GET: Ativos/Create
public ActionResult Create()
{
return View();
}
// POST: Ativos/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(AtivoViewModel ativo)
{
try
{
var client = WebApiHttpClient.GetClient();
string ativoJSON = JsonConvert.SerializeObject(ativo);
HttpContent content = new StringContent(ativoJSON, System.Text.Encoding.Unicode, "application/json");
var response = await client.PostAsync("api/Ativos", content);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
catch
{
return Content("Ocorreu um erro.");
}
}
// GET: Ativos/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/Ativos/" + id);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var ativo = JsonConvert.DeserializeObject<AtivoViewModel>(content);
if (ativo == null) return HttpNotFound();
return View(ativo);
}
return Content("Ocorreu um erro: " + response.StatusCode);
}
// POST: Ativos/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 async Task<ActionResult> Edit(AtivoViewModel ativo)
{
try
{
var client = WebApiHttpClient.GetClient();
string ativoJSON = JsonConvert.SerializeObject(ativo);
HttpContent content = new StringContent(ativoJSON, System.Text.Encoding.Unicode, "application/json");
var response =
await client.PutAsync("api/Ativos/" + ativo.ID, content);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
catch
{
return Content("Ocorreu um erro.");
}
}
// GET: Ativos/Delete/5
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var client = WebApiHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("api/Ativos/" + id);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
var ativo = JsonConvert.DeserializeObject<AtivoViewModel>(content);
if (ativo == null) return HttpNotFound();
return View(ativo);
}
return Content("Ocorreu um erro: " + response.StatusCode);
}
// POST: Ativos/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
try
{
var client = WebApiHttpClient.GetClient();
var response = await client.DeleteAsync("api/Ativos/" + id);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
{
return Content("Ocorreu um erro: " + response.StatusCode);
}
}
catch
{
return Content("Ocorreu um erro.");
}
}
}
I'll post only the Create view of PlanoManutencao, which is:
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Nome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nome, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Nome, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Observacoes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Observacoes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Observacoes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Permanente, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Permanente)
#Html.ValidationMessageFor(model => model.Permanente, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="ativos">Assets</label>
<div class="col-md-10">
#Html.DropDownList("ativos",String.Empty)
#Html.ValidationMessageFor(model => model.Ativos)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataCriacao, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataCriacao, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DataCriacao, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
EntityFramework creates the join table in the WebAPI DB just fine, but when i create one PlanoManutencao with one Ativo it creates the PlanoManutencao but does not add anything to the join table. I reckon it my be a mistake i have in the repositories or controllers, but i cannot solve it. I also followed lots of tutorials, none of which seem to solve my problem.
I'm sorry for the long explanation, and thank you in advance, only for reading such a text :)
Try doing this inside your PlanosManutencaoRepo:
public class PlanosManutencaoRepository : IPlanosManutencaoRepository
{
public PlanoManutencao Create(PlanoManutencao planoManutencao)
{
foreach(var a in planoManutencao.Ativos)
{
context.Ativos.Attach(a);
}
context.PlanosManutencao.Add(planoManutencao);
context.SaveChanges();
return planoManutencao;
}
}

Make List of Items C# MVC [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a very big issuse here. I'm trying to make a list off all cars and push them to View, but it doesn't work as I assume. Any idea how can I do that ?? I would be very thankfull
Here is my Car Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Automarket.Models;
using System.Data.Entity;
using System.Web.Script.Serialization;
using System.Net;
namespace Automarket.Controllers
{
public class CarController : Controller
{
OurDBContext db = new OurDBContext();
private object Viewbag;
private readonly object ds;
// GET: Automarket
public ActionResult Index()
{
List<Marke> marke = db.Marke.ToList();
List<Modeli> modeli = db.Modeli.ToList();
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string deps = oSerializer.Serialize(modeli);
ViewData["deps"] = deps;
ViewData["marke"] = marke;
ViewData["modeli"] = modeli;
return View(db.car.ToList());
}
// GET: Cars/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// GET: Cars/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CarID,Make,Model,Price,Registration,Mileage,FuealType,Country,ZipCode,Picture")] Car car)
{
if (ModelState.IsValid)
{
db.car.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
// GET: Cars/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CarID,Make,Model,Price,Registration,Mileage,FuealType,Country,ZipCode,Picture")] Car car)
{
if (ModelState.IsValid)
{
db.Entry(car).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(car);
}
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Car car = db.car.Find(id);
if (car == null)
{
return HttpNotFound();
}
return View(car);
}
// POST: Cars/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Car car = db.car.Find(id);
db.car.Remove(car);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Here is my Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Automarket.Models
{
public class Car
{
public int CarID { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public float Price { get; set; }
public int Registration { get; set; }
public double Mileage { get; set; }
public string FuealType { get; set; }
public string Country { get; set; }
public int ZipCode { get; set; }
public string pathToImage { get; set; }
}
}
To show a list of objects in your view, bascally, you need:
In Controller, send a list of objects to View using View(<data>) method:
public ActionResult Index() {
OurDBContext db = new OurDBContext();
return View(db.car.ToList());
}
In View, receive the list of objects in Model variable:
#model List<Car>
<html>
...
<body>
#foreach(var item in Model) {
<p>#item.Property</p>
}
</body></html>

Dropdown value gets null value

I use breakpoint debug it my ClientsId always come null and display on my payments index always is the first value of my Dropdownlist
Model:
public class Payments
{
[Key]
public int PaymentsId { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
}
ViewModel:
public class PaymentsViewModel
{
[Required(ErrorMessage = "Please select a client")]
[Display(Name = "Client")]
public int SelectedClient { get; set; }
public IEnumerable<SelectListItem> Client { get; set; }
}
GET CONTROLLER:
public ActionResult Create(Payments model)
{
var liste= new PaymentsViewModel
{
Clients = new SelectList(db.ClientList, "ClientId", "ClientName")
};
return View(liste);
}
POST CONTROLLER:
public ActionResult Create([Bind(Include = "....")] PaymentsViewModel model)
{
if (ModelState.IsValid)
{
model.PaymentsCreate();
return RedirectToAction("Index", "Payments");
}
return View(model);
}
CREATE VIEW:
#Html.DropDownListFor(m => m.SelectedClient, Model.Clients, "-Please select-", new { #class = "form-control" })
</div>
</div>
--------------------------------------------UPDATE---------------------------------------------------
EDIT CONTROLLER (GET):
public ActionResult Edit(int? id, PaymentsViewModel model)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Payments payments = db.PaymentsList.Find(id);
if (payments == null)
{
return HttpNotFound();
}
return View();
}
EDIT CONTROLLER (POST)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PaymentsId,Paymentnumber,PaymentDate,Amount,Discount,Reference,Total")] Payments payments)
{
if (ModelState.IsValid)
{
db.Entry(payments).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payments);
}
You should add a ClientsId initialization from model.SelectedClient at PaymentsCreate functions like: ClientsId = model.SelectedClient. And then you need to add SelectedClient string to properties enumeration at Create (post) method to Bind(Include.... attribute

NullReferenceException on DropDownListFor after [HttpPost]

In my application I'am populating a dropdownlist from database using ADO Entity Framework, after this when i try to submit the form the value of the dropdown list it is giving Null reference exception.
Error Code (in INDEX.ASPX)
<%: Html.DropDownListFor(model => model.race, Model.Races, "--Select--")%> <--error
<%: Html.ValidationMessageFor(model => model.race)%>
CONTROLLER (in NewPersonController)
public ActionResult Index()
{
Person person= new Person();
return View(new PersonFormViewModel(person));
}
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) //Also not enter the race parameter
{
personRepo.Add(person);
personRepo.Save();
}
return View(); // When return the view I get the error
}
MODEL (in PersonFormViewModel)
public class PersonFormViewModel
{
public Person Person {
get;
private set;
}
public SelectList Races
{
get;
private set;
}
public string race
{
get { return Person.race; }
set { Person.race = value; }
}
public PersonFormViewModel(Person person)
{
Person = person;
RaceRepository repository = new RaceRepository();
IList<Race> racesList= repository.FindRaces().ToList();
IEnumerable<SelectListItem> selectList =
from c in racesList
select new SelectListItem
{
Text = c.race,
Value = c.id.ToString()
};
Races = new SelectList(selectList, "Value", "Text");
}
}
IN VALIDATION MODEL
[MetadataType(typeof(Person_Validation))]
public partial class Person {
}
public class Person_Validation
{
[Required(ErrorMessage = "Required race")]
public string race
{
get;
set;
}
}
Can you help me please? Thank you.
In the POST method you have to give the same type of model to the view.
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid)
{
personRepo.Add(person);
personRepo.Save();
}
return View(new PersonFormViewModel(person));
}
You're not passing the ViewModel in the post action.
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) //Also not enter the race parameter
{
personRepo.Add(person);
personRepo.Save();
}
return View(new PersonFormViewModel(person));
}
Or maybe
[HttpPost]
public ActionResult Index(Person person)
{
if (ModelState.IsValid) //Also not enter the race parameter
{
personRepo.Add(person);
personRepo.Save();
}
return RedirectToAction("Index");
}

Categories

Resources