Reputation: 580
newbie here. I get the error The resource cannot be found.
when requesting url /event/details/3.
I use a MVVM.
My schema is simple. I have "Event", "Person" and "PersonInEvent" tables. "PersonInEvent" is a junction table for the two others (holds the foreign keys).
I am trying to display in the "Details" view the event's data with its id (/event/details/3). The event's id is passed to the "Details" controller action, which instantiates my ViewModel that hold an event object. I set this event to be the one with the id that I receive when the viewmodel is created.
According to my controller (see below) I get the error because vm.Event == null
. But I can't find a way to solve this issue. I have the feeling that it is a basic programming problem, such as how my "Event" property in my viewmodel is created. But still I cannot figure out the solution. Thanks in advance.
My controller's Details action:
[HttpPost] // this was the problem
[ValidateAntiForgeryToken]
public ActionResult Details(int id)
{
var vm = new EventDetailsViewModel(id);
if (vm.Event == null)
{
return HttpNotFound(); // I get the error because of this imo
}
return View("Details", vm);
}
My view model:
public class EventDetailsViewModel
{
private readonly ApplicationDbContext _db = new ApplicationDbContext();
private readonly int _eventIdVm;
private Event _event;
public EventDetailsViewModel(int id)
{
_eventIdVm = id;
_event.EventId = id;
}
public Event Event
{
get
{
return _event = _db.Event.Find(_eventIdVm);
}
set { _event = value; }
}
public List<Person> Persons
{
get
{
if (!_db.PersonInEvent.Any(pe => pe.EventId == _eventIdVm))
{
return Enumerable.Empty<Person>().ToList();
}
var personsOfEvent = _db.PersonInEvent.Where(pe => pe.EventId == _eventIdVm)
.Select(pe => pe.Person)
.ToList();
return personsOfEvent;
}
}
}
My view just in case:
@model BillSplittingWebApp.ViewModels.EventDetailsViewModel
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Event</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Event.EventName)
</dt>
<dd>
@Html.DisplayFor(model => model.Event.EventName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Event.EvenTimeBegin)
</dt>
<dd>
@Html.DisplayFor(model => model.Event.EvenTimeBegin)
</dd>
</dl>
</div>
EDIT: Problem was the attribute [HttpPost]
that I forgot to remove for the action.
Upvotes: 0
Views: 653
Reputation: 3889
This is a poor way MVC is a Pattern it's self. ViewModels should not be referencing databases directly. However, the issue is that in your viewModel you have declared a private Event Object. In the constructor you are trying to set the id of this object without first instanciating a new instance.
You can remove this line of code as it's not doing anything useful in the constructor anyway:
_event.EventId = id;
Upvotes: 3