问题
I'm trying to refactor some of my code and i'm wondering if it is possible something like this:
This is part of my cshtml:
<a href="@Url.Action("Vote", "Ideas", new { id = item.Idea.Id, pageMetadata = Model.PageMetadata, numberOfVotes = 2 })">
This is invoking action:
public ActionResult Vote(string id,PageMetadata pageMetadata, int numberOfVotes = 1)
And PageMetadata
is my class.
When im debbuging in cshtml site pageMetadata
is correct,but when action is invoking pageMetadata
it's becoming to null
. Do I some stupid mistake or all idea is wrong?
Thanks for any help.
回答1:
Query strings are like dictionary : {key, value} pairs. Therefore you cannot pass your class objects in query strings.
But, what you can do, is to pass this the id for your model object and then use that id to load your object on server.
Right now, you are working on a wrong notion ! :-)
回答2:
One other option is to serialize / deserialize the object for example:
<a href="@Url.Action("Vote", "Ideas", new { id = item.Idea.Id, pageMetadata = JsonConvert.SerializeObject(Model.PageMetadata), numberOfVotes = 2 })">
in the controller:
public ActionResult Vote(string id,string pageMetadata, int numberOfVotes = 1)
var pageMetadataObj = JsonConvert.DeserializeObject<PageMetadata>(pageMetadata)
Note: this will expose your object properties to the browser and could add significant size to the webpage depending on the number and type of objects.
来源:https://stackoverflow.com/questions/8938210/is-it-possible-to-pass-object-as-route-value-in-mvc-3