ASP.NET MVC Partial View Help - asp.net-mvc

I have created a partial view in my asp.net mvc solution that will show a list of items from a database. However I get an error saying: Object reference not set to an instance of an object.
I'm not sure why this is happening because as far as I'm concerned everything is fine. The list of items are venues which is controlled via VenuesController BUT the partial view is inside the /shared/ folder and NOT the /venues/ folder for the views so is asp.net complaining because it's not linking the two together?
This is the code I have in my VenuesController:
//
// GET: /Venues/
public ActionResult Index()
{
return View(_repository.ListAll());
}
public ActionResult VenuesList()
{
return PartialView("VenuesList",_repository.ListAll());
}
The Index() works fine and displays the data in /Views/Venues/Index.aspx but the VenuesList() throws the error :/
Thanks.

The error message that you mention:
Object reference not set to an instance of an object.
typically deals when a property of a collection is referenced and it is null. You might want to make sure that the list of items is either:
Not empty.
Instantiated properly.
Any code from the Controller-side of things might make this a bit easier to figure out.
Update:
I'm not completely sure what the Venue model looks like, however two things could be occurring here.
In the constructor for Venue (which should be passed the list from your repository),
the List property inside of Venue is never being instantiated prior to Adding the
items in.
or
The repository is not returning any values.
Additional code displaying the Venue class and it's constructor might be helpful.

Make sure that any properties in your model that you reference in your partial view are not null. I've had similar cases where the model passed into the partial view has some null fields that, when rendered, throw NullReferenceExceptions.
E.g. something like
<%: Model.Property %>
or, especially:
<%: Model.Property.ChildProperty %>
i.e. if "Property" is null, then trying to access "ChildProperty" WILL throw a NulLReference exception.

Related

Render a partial view with single model from a partial view using an IEnumerable

I am trying to figure out how to render a single model from a view that is using an IEnumerable of that model. I can't seem to figure out how to send it using the razor
Right now I am getting the error:
MyApp.Models.DefectsVM' is a 'type' but is being used like a 'variable'
On this line in my main view(Under DefectsVM model I am trying to pass in):
#{Html.RenderPartial("~/Views/Defect/defectsPartial.cshtml", DefectsVM);}
My partial view has this in it to use a model:
#model MyApp.Models.DefectsVM
And my main view is using this:
#model IEnumerable<MyApp.Models.DefectsVM>
I am not sure what all other information is needed, let me know if I need to edit. But thank you for reading and taking your time to help.
You need to refer to your model with Model. But in your case, Model will return an IEnumerable<MyApp.Models.DefectsVM>, so you will need to iterate over that, and then render your partial.
Something like:
foreach(var defectsVM in Model)
{
#{Html.RenderPartial("~/Views/Defect/defectsPartial.cshtml", defectsVM);}
}
Regardless of whether the IEnumerable contains one or more than one, it should work.

"Cannot Resolve Partial View X" in Umbraco 6 Html.Partial

I'm using Umbraco 6, and am using the new MVC architecture. I have a document type view template, which has a view model, which is instantiated and has it's properties populated from the controller. One of these properties is a collection, and in the view template I iterate through the collection and render out a Partial View with a separate view model, using 'Html.Partial("partialName", modelObject)'
The weird problem I'm having is that firstly, in Visual Studio I get a ReSharper warning telling me that it cannot resolve a partial view with that name (I have checked 50 times and I've spelt it correctly). Additionally when I then navigate to the page, I get the trusty ol' "Object reference not set to an instance of an object" YSOD.
I have debugged the code, and the controller action is hit fine, the logic to instantiate the view model for the document type template works fine, and populates the properties correctly, I've also made sure the properties are still set inside the view and the loop for rendering out the collection items correctly instantiates a view model object per collection item and sets the properties correctly. It breaks when it hits the Html.Partial.
Document Type View Code below:
#foreach (KeyValuePair<decimal, IPublishedContent> result in Model.Results)
{
PropertySearchResultViewModel model = ObjectMapper.SearchResultToViewModel(result);
Html.RenderPartial("PropertySearchResultDesktop", model);
}
Partial View Code below:
#using Production.Umbraco.Extensions.Models.ViewModels;
#inherits UmbracoViewPage<PropertySearchResultViewModel>
<article id="property-result-#Model.Node.Id.ToLower()">
<p>#Model.Node.Name</article>
<p>Distance: #Model.Distance Miles</p>
</article>
Here is a screenshot of my VS Solution tree:
The 'NewHomes.cshtml' document type view template is returned from the NewHomesController and the view is calling the 'PropertySearchResultDesktop.cshtml' partial view, which was created from the Umbraco back office, and was placed their automatically.
The Umbraco website says that you can and should place your partial views here
http://our.umbraco.org/Documentation/Reference/Mvc/partial-views
But no matter what I try to do, it just wont render the partial. I've seen one other question about this on SO but the answer was just to place it in MacroPartials instead, which I dont want to do as part of the benefit of using Partial Views in Umbraco 6 is that they inherit from UmbracoViewPage with a strongly typed model declaration, which MacroPartials don't.
Has anyone encountered this before?
Fixed. The issue was with the model I was passing to the document type view from the controller.
In the Umbraco documentation it says, you can create a controller to hijack the Umbraco route and serve up your own view with a custom model, like so:
public ActionResult Index(RenderModel model)
{
SearchResultsViewModel viewModel = new SearchResultsViewModel
return CurrentTemplate(viewModel);
}
and in my view I had:
#inherits UmbracoViewPage<SearchResultsViewModel>
However, it seems as though, in order to do that, you must make sure your custom view model in inherits from RenderModel with a constructor that takes RenderModel as a parameter and then sets some properties on the base object, like so:
public class SearchResultsViewModel :RenderModel
{
public SearchResultsViewModel(RenderModel model) : base(model.Content, model.CurrentCulture)
{
}
}
Previously, my view model had not inherited from anything and had a parameterless constructor.
This article led me to the right answer.
http://www.ben-morris.com/using-umbraco-6-to-create-an-asp-net-mvc-4-web-applicatio
Also, as a side note, I still get the ReSharper warning of "Cannot resolve partial view PropertySearchResultDesktop" but I think that's a ReSharper bug rather than an error.
Even with a full path and file extension in the call, it still complains.
I do find it odd though that while debugging, even with my old controller code, no exception was thrown at the model binding stage or inside the controller, or in the view until it go to the Html.Partial call.
Anyway, I hope this helps anyone having the same issue.

MVC nested model collection is empty (not null)

I have a model that has a property which is a collection. I can successfully bind from the edit actions, for example:
[HttpGet]
public ActionResult Edit(string id)
{
// code here
return this.View(complexModel);
}
[HttpPost]
public ActionResult Edit(ComplexModel complexModel)
{
// code here
return RedirectToAction("AnotherAction")
}
In the post method I can successfully receive all the object properties, including the collection one. However I have another view that can invoke the Edit action. When this happens I can see that the html rendered is the same (i.e. the nested property info is there). When I save the changes in the post Edit I receive all the correct properties with one exception - the collection propery has zero items.
Where do I have to search for the problem?
Update:
I am properly iterating through the collection and displaying all items with EditorFor; however when coming from a differnt view (the different view is in another controller and the Edit link is placed in a Display Template - if that makes any difference) with the same exact model I can see that the html is the same since all the properties of the collection are there.
Ok, false alarm. I figured it out - I am invoking the action method using #Html.ActionLink; I was passing the whole model instead of just the id. I do not know for what silly reason things got messed up, but they are ok now.
What does your Edit view look like? You need to iterate over all the items in the collection as form elements.

How can I render a list of objects using DisplayFor but from the controller in ASP.NET MVC?

Here's the scenaio, I have an Employee object and a Company object which has a list of employees.
I have Company.aspx which inherits from ViewPage<Company>.
In Company.aspx I call
Html.DisplayFor(m => m.Employees).
I have an Employee.ascx partial view which inherits from ViewUserControl<Employee> in my DisplayTemplates folder.
Everything works fine and Company.aspx renders the Employee.ascx partial for each employee.
Now I have two additional methods on my controller called GetEmployees and GetEmployee(Id).
In the GetEmployee(Id) action I want to return the markup to display this one employee, and in GetEmployees() I want to render the markup to display all the employees (these two action methods will be called via AJAX).
In the GetEmployee action I call
return PartialView("DisplayTemplates\Employee", employee)
This works, although I'd prefer something like
return PartialViewFor(employee)
which would determine the view name by convention.
Anwyay, my question is how should I implement the GetEmployees() action?
I don't want to create any more views, because frankly, I don't see why I should have to.
I've tried the following which fails miserably :)
return Content(New HtmlHelper<IList<Of DebtDto>>(null, null).DisplayFor(m => debts));
However if I could create an instance of an HtmlHelper object in my controller, I suppose I could get it to work, but it feels wrong.
Any ideas? Have i missed something obvious?
I've always solved this by having a Partial View which loops over an IEnumerable<T> and calls Html.DisplayFor() on each item, but then I didn't even know you could call Html.DisplayFor() on an IEnumerable<T> and have it automatically render each templated element until you said so in your question. Thanks for that, by the way! :)
In any case, I think your best bet is to simply return a PartialView() which accepts a collection of Employees and renders them one at a time calls Html.DisplayFor(). It's not as elegant as returning an HtmlHelper from your controller, but at least it's simple enough to implement.

ASP.Net MVC DefaultModelBinder not binding properties on POST

I'm facing a really strange problem that has me smoked.
I have a fairly simple scenario where I have a strongly typed view that is correctly populated from the controller on the GET, but then when it POSTS the form to the controller, the Reqeust is full of all the right values and right key names for the default model binder to correctly populate one of my model objects, and the DMB creates the correct opject, but it never populates any of the properties, they're all in their default state.
This was working before, the only changes I can think of were that I tried a custom modelbinder (then removed it; double checked to make sure I'm not still using that), and I refactored the model to have a base class with some of the props.
Any thoughts?
A very similar scenario - that the DefaultModelBinder is - essentially - not binding to your model, arrise if you would give your bound model object the same name as one of its properties:
Model
Public Property ArbitraryName1 As Integer
Public Property Answer As String
Public Property ArbitraryName2 As Boolean
View
<p/> ... #Model.ArbitraryName1
<p/> Answer: #Html.TextBoxFor(Function(model) model.Answer)
<p/> ... #Html.CheckBoxFor(Function(model) model.ArbitraryName2)
Controller
<HttpPost()>
Function Index(answer As Model) As ActionResult
' answer is Nothing
End Function
(Using ASP.NET MVC 3)
Got it. The model had been refactored in a way which naturally affected the ability of the mdoel binder to populate it.
The name of your input param do not have to be equal to some property name of the object. Remember that all data coming as an array of name -> value and the default binding use the names for make the relation work.
I had this behaviour arise by moving two properties from the top of the class to further down. I still can't work out why this stopped the binding of a third property from working (so this isn't a solution so much as a 'watch out for') but I repeated the change multiple times and each time the binding went from working to not working.
I also found that after making this change I sometimes had to 'Clean' the solution for the binding to start working again.

Resources