开发者

Dynamic typecasting in asp.net mvc Edit action: how can I handle multiple datatypes without throwing an exception?

开发者 https://www.devze.com 2022-12-15 10:56 出处:网络
I\'m making a generic MVC viewer/editor for data objects I\'ve designed, modeled after ActiveRecord. The data objects are completely generic, they can have primary keys that are strings, ints, int16s

I'm making a generic MVC viewer/editor for data objects I've designed, modeled after ActiveRecord.

The data objects are completely generic, they can have primary keys that are strings, ints, int16s, whatever the database uses (the persistence layer at this organization uses all sorts of datatypes for primary keys and I want this MVC "browser/editor" to handle them all).

Creating the Edit links in the Index view is easy:

Response.Write("<td>" + Html.ActionLink("Edit", "Edit", new { id = pkValue }) + "</td>");

The problem is on the other side, in the Edit action:

public ActionResult Edit(object id)

Anything other than a string throws an exception when I try to use id as the sole element of an array of parameters to a static "select" method invoked via reflection to retrieve a hydrated data object to edit from the database:

object[] parameters = { id };
list = (List<T>)select.Invoke(null, parameters);

I know the CLR type of the parameter, and I know the "real" type of object id. Am I supposed to use some kind of gnarly case statement to do the type conversion manually, or is there a trick I can use to do the type conversion using the type of the parameter?

Can/Should I overload the ActionResult Edit() to take int, int16, int32, etc?

What should I do here to ensure that no matter the "real" type of id, I can pass it into the database without an exception being thrown?

Here's what I've tried so far:

I made my generic controller take two type param开发者_运维技巧eters, one for the data object and another for the primary key datatype:

public class CoreDataController<t,T> : Controller  where T:IDataObjectBase<T>

Then I tried this move:

id = (t)id;
object[] parameters = { id};

BZZZRT! "the specified cast is invalid". id is "2" and t is int?


Can you supply more code details for the select method and the Stored Proc or Query that you are executing to the pull data.

I would currently suggest to pass the value of id parameter to select in the following manner.

if(id != null)
  Select(id.ToString());
0

精彩评论

暂无评论...
验证码 换一张
取 消