如何解决如何在ASP MVC的Json文件中追加记录?
//这是我已经实现的。这很好。但是问题是,当我再次提交数据时,旧数据将被删除。文件中仅显示最后插入的数据。 保存时,我希望将所有数据保存在Json文件中。
如果有人有主意,请帮助我。
print(x,y)
# [-0.0008,6e-06,-5.55e-06] [28.0,-4500.0,-62.0]
解决方法
我没有您的UserData实现,因此我根据您的评论猜测了它的外观。如果文件存在,则需要在覆盖之前回读该文件的内容。我使用的是Json.NET,但从未使用过您正在使用的特定序列化程序,但我假设它可以工作。您可以执行以下操作:
public class UserData
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string OfficeName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int RoleId { get; set; }
public string RoleName { get; set; }
}
public ActionResult Index(UserData model)
{
try
{
string path = Server.MapPath("~/App_Data/output.json");
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonData;
List<UserData> userDataList = new List<UserData>();
if (System.IO.File.Exists(path))
{
// Read from existing file.
jsonData = System.IO.File.ReadAllText(path);
// Fill in the list with the existing user data.
userDataList.AddRange(serializer.Deserialize<List<UserData>>(jsonData));
}
// Add the new user data to the end of the list.
userDataList.Add(model);
// Generate JSON based on the complete list.
jsonData = serializer.Serialize(userDataList);
// Write that JSON to a file.
System.IO.File.WriteAllText(path,jsonData);
TempData["msg"] = "Json file Generated! check this in your App_Data folder";
}
catch (Exception e)
{
}
return RedirectToAction("Index");
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。