0

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();
            }
        }
    }
liamcook
  • 143
  • 2
  • 10

1 Answers1

0

You're discarding your MajesticData object as soon as you construct it from the json. You'd need some code to extract data from that and place it in your ViewBag (or write it out somewhere else).

But I will say it does look odd that you only call the API if the ModelState isn't valid...

Dylan Nicholson
  • 1,301
  • 9
  • 23
  • Nicoholson Thanks for the reply! Oh I see, I followed this thread https://stackoverflow.com/questions/34043384/easiest-way-to-parse-json-response. So I have a model created which will accept every variable from the object, how do I save it the answer ended so I assumed that was it, since http://json2csharp.com/ gave my model in 4 classes. Sorry if this is simple in reality just can't figure it out! – liamcook Nov 19 '17 at 19:22
  • It's definitely not enough just to "save" it to a local variable. You can copy the relevant properties to the ViewBag so they'll be available when rendering the page for the client, or write them to a database table if you need to access them later. BTW you can make your code shorter if you use WebClient.DownloadString() to call the API. – Dylan Nicholson Nov 19 '17 at 19:26
  • From what I understand does that not create an object of the same variables as the MajesticData model would there not be a way to save this straight to the database? I don't exactly get where the data resides at this point this is my issue. Ahh great thanks! Yeah I spent so much time trying to figure out the code I didn't realise it was in the non-valid state so it wasn't even being called haha... – liamcook Nov 19 '17 at 19:33
  • If you have a Database table using a schema that matches `MajesticData` then yes, you could add it straight to the database, with something like `db.MajesticDatas.Add(r); db.SaveChanges()`. – Dylan Nicholson Nov 19 '17 at 19:59
  • Awesome I thought I could! However now i'm getting an error saying not all code paths return a value? I added the full code as an edit! Thanks for your time – liamcook Nov 19 '17 at 20:24
  • Well that's exactly as it says - you need to return an `ActionResult`, usually using `View( )` or `RedirectToAction( )` as per your original example. This determines what will happen on the client side. – Dylan Nicholson Nov 19 '17 at 20:42