views:

46

answers:

2

this is my renderparial

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<a href='<%= Url.Action("Edit", new {id=Model.ID}) %>'>
                    <img src="<%= Url.Content("~/img/pencil.png") %>" alt="Edit" width="16" /></a>

I basically want to call it in this way:

<% Html.RenderPartial("edit", new { ID = item.hlpb_ID }); %>

however, this gives me a runtime error 'object' does not contain a definition for 'ID'

so how do I send an on the fly created nameless object (because i guess thats what it is) to a renderpartial? like this works for Url.Action

+1  A: 

You can only call members of an object directly when you use a strongly typed view.

If you want to pass an dynamic object to a RenderPartial your pretty much stuck using reflection or the dynamic keyword to access properties you don't know at runtime. Doing this is an extremely bad practice. Generally you know what objects get passed to a view because you have to render them.

For more information about how to use the dynamic keyword check here:

http://weblogs.asp.net/shijuvarghese/archive/2010/02/03/asp-net-mvc-view-model-object-using-c-4-dynamic-and-expandoobject.aspx

jfar
so how would a strongly typed class look and how would i use it, i need to be able to send an ID and optional paramters for Url.Action.
Stefanvds
http://nerddinner.codeplex.com/ has some good examples.
jfar
+1  A: 

If it is always an ID you are passing in, why don't you just update your Partial View to accept Nullable<int> instead e.g.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<int?>" %>
<a href='<%= Url.Action("Edit", new {id=Model}) %>'>
    <img src="<%= Url.Content("~/img/pencil.png") %>" alt="Edit" width="16" />
</a>

Then your Edit action in the controller would look something like:

public ActionResult Edit(int? id)
{
    if (id.HasValue)
        // do something with id
    else
        // do something when no id supplied
}

Attempting to pass in a dynamic object seems pointless if it is just the ID you are interested in. If you have other information you need to use from the object you should consider a custom ViewData class that you can populate and pass into the View instead.

James
it's not always the ID. basically i need to be able to send the things i use in Url.Action. that's an ID, and optional paramters.
Stefanvds
Your view should know about your Model so my advice would be to have a custom `ViewData` class for this particular view with all the relevant properties.
James