0

I have a controller which returns a view.

Within the view I render a common shared partial view, and pass parameters in to it:

<div class="tab-pane" id="tab-sla">@{Html.RenderPartial(
        "./_sla",
        new
        {
            ContentTitle = "Service Level"
        });
    }
</div>

However whenever in the partial view _sla I try and access the property ContentTitle, it throws an error 'object' does not contain a definition for 'ContentTitle'.

If i dump the model properties with @Model.ToString() it shows { ContentTitle = "Service Level" }.

Can someone please advise what I am doing wrong and how this can be fixed?

morleyc
  • 2,169
  • 10
  • 48
  • 108
  • 2
    possible duplicate of [MVC Razor dynamic model, 'object' does not contain definition for 'PropertyName'](http://stackoverflow.com/questions/4862122/mvc-razor-dynamic-model-object-does-not-contain-definition-for-propertyname) – volpav Jan 04 '14 at 19:33

2 Answers2

0

This might help (taken from this SO answer, thanks to Lucas):

According to David Ebbo, you can't pass an anonymous type into a dynamically-typed view because the anonymous types are compiled as internal. Since the CSHTML view is compiled into a separate assembly, it can't access the anonymous type's properties.

You may also try using ViewData when accessing model properties. Helps me sometimes:

<h1>@ViewData["ContentTitle"]</h1>

Hope this helps.

Community
  • 1
  • 1
volpav
  • 5,090
  • 19
  • 27
  • @JohnH Yes, because I had some additional information (which might be useful) to share. – volpav Jan 04 '14 at 19:39
  • 1
    @JohnH and that's why I'd prefer this question to be closed ;-) The workaround that I mentioned might be enough, though, thus the answer (I don't know whether the author wants to go for a normal model type). – volpav Jan 04 '14 at 19:44
  • Thanks, makes sense now, weirdest thing is i am doing the same from within a partial view that calls another partial view and that works OK. I will create a model before using it, or just use `@model string` and pass in a string (a workaround i just did) – morleyc Jan 04 '14 at 19:49
  • @g18c, see my answer in the linked question for full details on the anomaly you are experiencing. It's a real gotcha! – joshcomley Feb 07 '14 at 16:59
  • The view and the partial views are on the same assembly. – kazinix Apr 26 '17 at 05:29
0

For full details please see the question and my answer here:

MVC Razor dynamic model, 'object' does not contain definition for 'PropertyName'

Essentially, the most likely reason it stopped working is because you have another view in the same folder with a model type that is not resolvable.

Correct the offending view with the broken model type, clean and rebuild the solution and it should work again.

Community
  • 1
  • 1
joshcomley
  • 28,099
  • 24
  • 107
  • 147