简体   繁体   中英

Append to a Json object in MVC controller in ASP.NET before sending data to the View

I am building an MVC application in ASP.NET. In my Index Controller I am calling an API, get the data and pass them to the view. This works well and I have no problem getting data back in my View.

public ActionResult Index()
{
    Base model = null;
    var client = new HttpClient();
    var task =
    client.GetAsync(
    "http://example.api.com/users/john/profile")
    .ContinueWith((taskwithresponse) =>
    {
        var response = taskwithresponse.Result;
        var readtask = response.Content.ReadAsAsync<Base>();
        readtask.Wait();
        model = readtask.Result;

    });
    task.Wait();

    return View(model);
}

My Model is following:

public class Base
{
    public Data data { get; set; }
}

public class Data
{
    public Profile profile { get; set; }
    public Credit credit { get; set; }
}

public class Profile
{
    public String firstname { get; set; }
    public String lastname { get; set; }
}

public class Credit
{
    public int amount { get; set; }

    public string balance { get; set; }

}

The API returns data in this format:

{

"data": {
    "profile": {
        "firstname": "John,
        "lastname": "Newman",
    },
    "credit": {
        "amount": 30,
    "neverbought" : false
    }
}
}

What I want to achieve now, is to add some more properties to the returned data. For example I want to add a state property to credit, which will be calculated according to amount and neverbought properties. But for now let's say the credit.state will always be "lowCredit".

So what I did, was to add Credit.state = "neverBought"; to my Controller before sending data to the View. Then I got some errors that my Credit class does not contain a definition for state. I added state property to my Credit Model, but then I got "An object reference is required for the non-static field, method or property.

Here is the code I used:

task.Wait();
model.credit.state = "lowCredit"; 
return View(model);

What am I doing wrong and what should I do to solve the problem?

It would be nice if you showed what code you used to throw the stated error. But I am going to assume that you probably did it before your async task completed. As long as you have the field available in your model

public class Credit
{
 public int amount { get; set; }
 public string state { get; set; }
 public string balance { get; set; }
}

then you should be able to just set it ( wait until the async finishes )

task.Wait();
model.data.credit.state = "lowCredit";
return View(model);

attempting to assign this value before the task has finished would be like trying to assign a value to null and will cause a runtime exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM