First of I am a complete beginner at MVC. How would I be able to display data from the database in the events table in a partial view if a certain boolean field is true.
This is my partial view:
@model IEnumerable<TheBigEvent.Models.RecommendedEvents>
<table>
<tr>
<td>
@Html.DisplayNameFor(model => model.Event_Name)
</td>
<td>
@Html.DisplayNameFor(model => model.Event_Date)
</td>
</tr>
<tr>
@foreach (var item in Model) {
<td>
@Html.DisplayFor(modelItem => item.Event_Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Event_Date)
</td>
}
</tr>
</table>
This is my controller
public ActionResult _RecommendedEvents()
{
var recommendedevents = from Events in db.Database1
select Events;
recommendedevents = recommendedevents.Where(s => s.Recommended.Equals(true));
return PartialView("_RecommendEvents", recommendedevents);
}
And the Code for displaying the partialview
@Html.Partial("_RecommmndedEvents")
This is the error I am receiving
[EDIT]
public ActionResult _RecommendedEvents(RecommendedEvents model)
{
model = new RecommendedEvents();
var recommendedevents = from Events in db.Database1
select Events;
recommendedevents = recommendedevents.Where(s => s.Recommended.Equals(true));
return View(model);
}
The error means your model is null,
PartialView()
is used when you are usingAjax
, otherwise you can write your code as below :This will go to the given controller and action that has to return a partialview with the correct model
object reference not set to an instance of an object has always been an un initialized list for me. try initializing recommendedevents before setting it. something like
replacing Events with whatever the type is.
the first parameter in Html.Partial is the partial name not the method call. you need to either pass the model to your view thought a view model and pass it to the partial
or load the partial through an ajax call. see my answer here for an example How do I render a partial form element using AJAX
The
@HTML.Partial()
function does not go through any controller action to render, it just renders the View's HTML in that spot in the document. And you aren't passing in theIEnumerable<TheBigEvent.Models.RecommendedEvents>
to that partial view, so when that partial renders, theModel
is null.Put the
IEnumerable<TheBigEvent.Models.RecommendedEvents>
object into your main page's View Model, or maybe on something in the ViewBag, and pass it to the partial view at the time you call the Partial method:@HTML.Partial("_RecommmndedEvents", ViewBag.RecommendedEvents)
In the top-level page's controller action, set that
ViewBag.RecommendedEvents
just like how you are instantiating it in your controller code above.