Mukla.C
Mukla.C

Reputation: 53

How to send a dictionary parameter to a URL.Action() in asp.net MVC3

Say I have a action method.......

public ActionResult DisplayXml(int viewId, Dictionary<string,string> parameter, string dataFormat )
        {
            string xml = "";
            return Content(xml, "text/xml");
        }

and in view I did.......

<iframe title="Xml" class="ResultDisplay" 
        src = "@Url.Action("DisplayXml", "OutputData", new {viewId = Model.ViewId, parameter = Model.Parameter, dataFormat = Model.DataFormat })">
</iframe>

Here parameter is a dictionary and I am getting null. How I can send it?????

Upvotes: 0

Views: 2707

Answers (1)

Martin Booth
Martin Booth

Reputation: 8595

You're trying to pass and arbitrary dictionary as a parameter in a querystring?

Its a pretty unusual requirement to need to serialize the contents of a dictionary to a query string parameter and back again. When generating querystring parameters, MVC will just call .ToString() on the values, and the Dictionary<,> object just uses the default implementation (which returns it's type)

Since this requirement is so uncommon, there's nothing built in to do this.. You can quite easily serialize the dictionary yourself to a string (perhaps json?) and then, change the parameter variable in your action to be a string. You'll have to deserialize the value back to a dictionary after that.

Before I provide much more of an example, I want to check you're absolutely sure this is what you want to do

Update:

Here is way of doing that (requires json.net):

    public ActionResult DisplayXml(int viewId, string parameterJson, string dataFormat )
    {
        var parameter = JsonConvert.DeserializeObject<Dictionary<string,string>>(parameterJson);

        string xml = "";
        return Content(xml, "text/xml");
    }

And use:

<iframe title="Xml" class="ResultDisplay" 
        src = "@Url.Action("DisplayXml", "OutputData", new {viewId = Model.ViewId, parameterJson = Newtonsoft.Json.JsonConvert.SerializeObject(Model.Parameter), dataFormat = Model.DataFormat })">
</iframe>

Upvotes: 2

Related Questions