读取Json数组并将其返回到索引视图



我在读取反序列化的json数组并将其返回视图方面遇到了挑战。我可以反序列化json,但不能继续返回值并将其发送到视图。

我得到错误,"名称用户在当前上下文中不存在"。知道为什么会发生这种事吗?。请在下方查看我的代码

控制器

public IActionResult Index()
{
return View();
}
//Method 
public async Task<IActionResult> UserCall()
{
using (var client = new HttpClient())
{
//Httpclient code goes here, removed for brevity

if (response.IsSuccessStatusCode)
{
var respstring = await response.Content.ReadAsStringAsync();
UserVM user = JsonConvert.DeserializeObject<userVM>(respstring); //the code work up to this point
}

return RedirectToAction("Index", "UserManage", user);//Error 'The name user does not exist in the current context'
}
}

型号

public class User
{
public string id { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string register { get; set; }
public string status { get; set; }
public string deregister { get; set; }
}
public class user
{
public IEnumerable<User> user { get; set; }
}

这是Json字符串

{
"user": [   
{
"id": "1",
"name": "Name1",
"surname": "Surname1",
"register": "2020-05-07",
"status": "A",
"deregister": "2021-05-06"
},
{
"id": "2",
"name": Name2
"surname": "Surname2",
"register": "2020-08-07",
"status": "L"
}
]
}

您需要将用户变量定义移动到if块之外,以便访问它。

//Method 
public async Task<IActionResult> UserCall()
{
using (var client = new HttpClient())
{
//Httpclient code goes here, removed for brevity
UserVM user = null; // <---- here
if (response.IsSuccessStatusCode)
{
var respstring = await response.Content.ReadAsStringAsync();
user = JsonConvert.DeserializeObject<userVM>(respstring); //the code work up to this point
}

return RedirectToAction("Index", "UserManage", user); //Error 'The name user does not exist in the current context'
}
}

最新更新