Reputation: 67
I create a folder "js" inside Script folder and create a file json with array citys and i try read this file on this folder and return a list to my select view.
{
"cidade": [
{ "Nome": "Curitiba" },
{ "Nome": "São Paulo" },
{ "Nome": "Rio de Janeiro" },
{ "Nome": "Santa Catarina" },
{ "Nome": "Rio Grande do Sul" },
{ "Nome": "Acre" },
{ "Nome": "Goias" }
]
}
My class:
public class Cidade {
public string Nome {
get;
set;
}
}
public class Cidades {
public IList < Cidade > cidades {
get;
set;
}
}
And my action :
public class Cidade {
public string Nome {
get;
set;
}
}
public class Cidades {
public IList < Cidade > cidades {
get;
set;
}
}
This is the error:
Upvotes: 2
Views: 10070
Reputation: 67
My final Code:
[HttpGet]
public ActionResult Get()
{
var json = System.IO.File.ReadAllText(Server.MapPath(@"~/App_Data/cidade.json"));
Cidade cidade = JsonConvert.DeserializeObject<Cidade>(json);
return View(cidade);
}
My class:
public class Cidades
{
public string Nome { get; set; }
}
public class Cidade
{
public List<Cidades> cidade { get; set; }
}
Upvotes: 0
Reputation: 4236
This code will have the json file path not the contents of json file:
var json = Server.MapPath("~/Scripts/js/cidade.json");
You should change it to following to read json contents:
var json = System.IO.ReadAllText(Server.MapPath("~/Scripts/js/cidade.json"));
You are also missing an s
in your json data. Your class has a property IList<Cidade> cidades
while your json has the key as cidad
Upvotes: 1