2

I'm trying to pass some parameters (a couple of strings) from a page to a partial view that is to be rendered in the main page. To do this, I'm passing an anonymously typed object, which keeps giving me a RuntimeBinderException. Given what I've tried, I'm not surprised to be getting the error, but I don't know what else to try.

Views\Home\PageWithPartialView.cshtml

@Html.Partial("DynamicPartialView", new { paramFromPageToPartialView = "value" })

Views\Shared\DynamicPartialView.cshtml

@model dynamic // Doesn't make a difference

@{
    // This is where I need to access and display the parameters 
    // passed from the main page

    // Throws RuntimeBinderException
    // Cannot apply indexing with [] to an expression of type 'object'
    var try1 = Model["paramFromPageToPartialView"];

    // Throws RuntimeBinderException
    // 'object' does not contain a definition for 'paramFromPageToPartialView'
    var try2 = Model.paramFromPageToPartialView;
}

If partial views aren't the way to do this, I'm open. The partial view has a couple hundred lines of code to produce, so custom HtmlHelpers don't seem manageable to me.

Logical Fallacy
  • 3,017
  • 5
  • 25
  • 41
  • 1
    Are the two bits of code both in the same assembly, out of interest? – Jon Skeet Feb 22 '12 at 20:05
  • I think so... The first is located in Views\Home\, and the other is located in Views\Shared\. The exception does occur in the partial view. – Logical Fallacy Feb 22 '12 at 20:09
  • So they're both in the same project? Hmm. I could understand it if they were in different assemblies. I'm not an MVC person... is there anything you can do to force them to be compiled "early"? (I don't know what the lifecycle is in MVC) That would make sure they're really in the same assembly. – Jon Skeet Feb 22 '12 at 20:13

1 Answers1

3

The ViewBag is designed to solve this kind of problem. Rather than consuming paramFromPageToPartialView in your partial from the Model, consume it from the ViewBag:

Views\Home\PageWithPartialView.cshtml

@{ViewBag.paramFromPageToPartialView = "value";}
@Html.Partial("DynamicPartialView")

Views\Shared\DynamicPartialView.cshtml

@model dynamic // Doesn't make a difference

@{
    var try3 = ViewBag.paramFromPageToPartialView;
}
Dan Davies Brackett
  • 9,811
  • 2
  • 32
  • 54
  • Bingo! I was pretty sure I was missing something... Thanks! – Logical Fallacy Feb 22 '12 at 20:27
  • This helped a ton with my current situation where I'm repeatedly rendering a partial view with slightly different types and am unable to refactor the underlying classes. I [ultimately went with reflection](http://stackoverflow.com/a/31306368/957950), but would have used this if the rest of the team knew .NET MVC well enough. – brichins Jul 09 '15 at 01:03