leora
leora

Reputation: 196499

How can i translate this PHP code to C# asp.net-mvc?

I have a javascript library that is expecting this from the server but the example is in PHP

<?php
/* http://www.example.com/json.php */
$array['E'] =  'Letter E';
 $array['F'] =  'Letter F';
 $array['G'] =  'Letter G';
 $array['selected'] =  'F';
 print json_encode($array);
 ?>

so I trying to find how to do the above in c# asp.net-mvc given that C# arrays don't take string keys . .

 public JsonResult MyAction()
 {
     return Json(...);
  } 

Upvotes: 0

Views: 90

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65079

What does the resulting JSON look like from that PHP code?

If its an object.. you could just return an anonymous object:

return Json(new {
    E = "Letter E",
    F = "Letter F",
    // etc...
});

If its a key-value pair, you could use a Dictionary:

return Json(new Dictionary<string, string>() {
    { "E", "Letter E" },
    { "F", "Letter F" },
    // etc...
});

Upvotes: 1

Martin Costello
Martin Costello

Reputation: 10862

Try this using anonymous types:

public JsonResult MyAction()
{
    return Json(
        new
        {
            E = "Letter E",
            F = "Letter F",
            G = "Letter G",
            Selected = "F",
        });
} 

Upvotes: 1

Related Questions