andy wilson
andy wilson

Reputation: 970

Get Json from Web api and pass to partial view from controller

At the moment I have this as my code:

 public ActionResult Search(SearchModel model)
    {
        string url = "http://10.0.2.31/testwebapi/api/data";
        WebClient wc = new WebClient();

        wc.QueryString.Add("forename", model.Forename);
        wc.QueryString.Add("surname", model.Surname);
        wc.QueryString.Add("caseid", model.CaseId);
        wc.QueryString.Add("postcode", model.Postcode);
        wc.QueryString.Add("telephone", model.Telephone);
        wc.QueryString.Add("email", model.Email);
        wc.QueryString.Add("title", model.Title);

        var data = wc.UploadValues(url, "POST", wc.QueryString);


        var responseString = Encoding.Default.GetString(data);

        return PartialView("~/Views/Shared/SearchResults.cshtml", responseString);

    }

    public class RootObject
    {
        public int Caseid { get; set; }
        public string Title { get; set; }
        public string Forename { get; set; }
        public string Surname { get; set; }
        public string Postcode { get; set; }
        public string Telephone { get; set; }
        public string Email { get; set; }
        public string DOB { get; set; }
        public string Mobile { get; set; }
        public string MaritalStatus { get; set; }
        public string LoanPurpose { get; set; }
        public bool CourtesyCall { get; set; }
        public string isOpen { get; set; }
    }

im not sure where i am going wrong i want it to be able to pull that data from the web api (which returns a json file). then what i want to do is send that data through to my partialview where a @foreach statement will put it into a table but i cant seem to get it to send the data it is interperating it as a string and i dont know why

this is how it is returning:

enter image description here

@model  string
@{ 
    Layout = null;
}

@foreach(var Case in Model)
{
    <p>@Case</p>
}

Partial view code.

This is what my partial now looks like:

@model  IEnumerable<Savvy_CRM_MVC.Models.RootObject>
@{ 
    Layout = null;
}
@foreach (var m in Model)
{
    <p>@m</p>
}

which when i run through the for each is gives me this Savvy_CRM_MVC.Models.RootObject

Upvotes: 0

Views: 1183

Answers (1)

Fran
Fran

Reputation: 6520

The problem is that you are binding you model to the raw JSON string.

you need to deserialize the JSON string to your RootObject class and use RootObject as the model for your view.

the following code user Newtonsoft JSON.net to deserialize the string;

var rootObjects = JsonConvert.DeserializeObject<RootObject[]>(responseString);

return PartialView("~/Views/Shared/SearchResults.cshtml", rootObjects);

and you view changes

@model IEnumerable<RootObject>

You are also going to need to change you view to display the properties of your model.

Upvotes: 1

Related Questions