Been working on learning APIs for a few days, found it a little difficult but managed to muster this from reading a fair amount of posts:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,domain,contact,contactname,price,type,TF,CF,RI,MJTopicsID,UserTableID")] Identifier identifier)
{
if (ModelState.IsValid)
{
db.Identifiers.Add(identifier);
db.SaveChanges();
return RedirectToAction("Index");
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
"https://api.majestic.com/api/json?app_api_key=KEY&cmd=GetIndexItemInfo&items=1&item0=http://www.majestic.com&datasource=fresh");
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string json2 = reader.ReadToEnd();
MajesticData r = JsonConvert.DeserializeObject<MajesticData>(json2);
}
ViewBag.MJTopicsID = new SelectList(db.MJTopicss, "ID", "ID", identifier.MJTopicsID);
ViewBag.UserTableID = new SelectList(db.UserTables, "ID", "userIdentity", identifier.UserTableID);
return View(identifier);
}
}
I then used http://json2csharp.com/ to create my models and changed the RootObject to MajesticData. I initialised the tables in my I then run this within the [httpPost] create action of a controller, though the create action happens fine and it commits data to the identifier table and returns the view, however no data is committed to the MajesticData model or others?
Update with Save:
public ActionResult ApiCall()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.majestic.com/api/json?app_api_key=KEY&cmd=GetIndexItemInfo&items=1&item0=http://www.majestic.com&datasource=fresh");
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string json2 = reader.ReadToEnd();
Datum newdata = JsonConvert.DeserializeObject<Datum>(json2);
db.Datums.Add(newdata);
db.SaveChanges();
}
}
}