Sending an unknown object to a RenderPartial in MVC
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 renderpa开发者_StackOverflow中文版rtial? like this works for Url.Action
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
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.
精彩评论