How do I return related entities in web api, and call web api from separate mvc application

How do I return related entities in web api, and call web api from separate mvc application



How can I return an entity with it's related entities in a Web API method, and call it from a MVC application.



I have a Web API in which I am returning a Person entity, I am also returning all the policies linked to the Person entity.


Person


Person



So a Person can have one or many Policies.


Person


Policies



So far I am able to do this in my Web API controller.



The problem is calling my Web API in a separate MVC application.



Currently I can only return the Person record in my MVC application, I am struggling to return the Person and all related Policies in my MVC application.


Person


Person


Policies



In my MVC .cshtml view I am calling the ViewModel to pass the data to all the fields in the Web API.


.cshtml



This is my WebApi Method



Web Api ViewModel



Policies Class



MVC Controller calling Web Api method



This is the mvc cshtml view I am displaying the data from the web api in


[Route("pklifeinsured")]
public IHttpActionResult GetRec(int pklifeinsured)

var model = new Amendments_Interface_VM();
using (var db = new TestLiveEntities())

var ctx = db.LifeInsureds.Where(l => l.pkLifeInsured == pklifeinsured).FirstOrDefault();
if (ctx != null)

model = new Amendments_Interface_VM

pkLifeInsured = ctx.pkLifeInsured,
IdNumber = ctx.IdNumber,
Surname = ctx.Surname,
FirstName = ctx.FirstName,
Initials = ctx.Initials,
fkGender = ctx.fkGender,
DateOfBirth = ctx.DateOfBirth,
fkTitle = ctx.fkTitle,
fkMaritalStatus = ctx.fkMaritalStatus,
fkSmokerStatus = ctx.fkSmokerStatus,
fkLanguage = ctx.fkLanguage,
fkCommunicationMethod = ctx.fkCommunicationMethod,
Mobile = ctx.Mobile,
HomeTel = ctx.HomeTel,
EmailHome = ctx.EmailHome,
WorkTel = ctx.WorkTel,
EmailWork = ctx.EmailWork,
Postal_AddressLine1 = ctx.Postal_AddressLine1,
Postal_AddressLine2 = ctx.Postal_AddressLine2,
Postal_AddressLine3 = ctx.Postal_AddressLine3,
Postal_AddressLine4 = ctx.Postal_AddressLine4,
Postal_AddressLine5 = ctx.Postal_AddressLine5,
Physical_AddressLine1 = ctx.Physical_AddressLine1,
Physical_AddressLine2 = ctx.Physical_AddressLine2,
Physical_AddressLine3 = ctx.Physical_AddressLine3,
Physical_AddressLine4 = ctx.Physical_AddressLine4,
Physical_AddressLine5 = ctx.Physical_AddressLine5
;
model.PolicyHolder = db.PolicyHolders.Where(x => x.fkLifeInsured == pklifeinsured).Select(p => new PolicyHolderVM

PolicyNumber = p.PolicyNumber,
DOC = p.DOC,
fkLifeInsured = p.fkLifeInsured,
PolicyStatus = p.PolicyStatus,
RelationshipToLifeInsured = p.RelationshipToLifeInsured,
Package = p.Package,
Name = p.Name,
ContactNumber = p.ContactNumber,
ID_Reg_Num = p.ID_Reg_Num,
EmailAddress = p.EmailAddress
).ToList();


return Ok(model);





public class Amendments_Interface_VM

public int pkLifeInsured get; set;
public string FirstName get; set;
public string Initials get; set;
public string Surname get; set;
public string fkTitle get; set;
public string fkGender get; set;
public string IdNumber get; set;
public Nullable<System.DateTime> DateOfBirth get; set;
public string fkMaritalStatus get; set;
public string fkSmokerStatus get; set;
public string fkLanguage get; set;
public string fkCommunicationMethod get; set;
public string WorkTel get; set;
public string Mobile get; set;
public string EmailWork get; set;
public string HomeTel get; set;
public string EmailHome get; set;
public string Postal_AddressLine1 get; set;
public Nullable<int> PA1_Id get; set;
public string Postal_AddressLine2 get; set;
public Nullable<int> PA2_Id get; set;
public string Postal_AddressLine3 get; set;
public Nullable<int> PA3_Id get; set;
public string Postal_AddressLine4 get; set;
public Nullable<int> PA4_Id get; set;
public string Postal_AddressLine5 get; set;
public Nullable<int> PA5_Id get; set;
public string Physical_AddressLine1 get; set;
public Nullable<int> PhyA1_Id get; set;
public string Physical_AddressLine2 get; set;
public Nullable<int> PhyA2_Id get; set;
public string Physical_AddressLine3 get; set;
public Nullable<int> PhyA3_Id get; set;
public string Physical_AddressLine4 get; set;
public Nullable<int> PhyA4_Id get; set;
public string Physical_AddressLine5 get; set;
public Nullable<int> PhyA5_Id get; set;

public IList<PolicyHolderVM> PolicyHolder get; set;






public class PolicyHolderVM

public int PolicyNumber get; set;
public Nullable<System.DateTime> DOC get; set;
public int fkLifeInsured get; set;
public string PolicyStatus get; set;
public string RelationshipToLifeInsured get; set;
public string Package get; set;
public string Name get; set;
public string ContactNumber get; set;
public string ID_Reg_Num get; set;
public string EmailAddress get; set;



public ActionResult Index(int? pklifeinsured)

var LifePolicy = new Amendments_Interface_VM();

using (var client = new HttpClient())

client.BaseAddress = new Uri(apiURL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.GetAsync($"apiURL/api/LifePol/pklifeinsured").Result;

if (response.IsSuccessStatusCode)

LifePolicy = response.Content.ReadAsAsync<Amendments_Interface_VM>().Result;


return View(LifePolicy);




@model WebApiTest_Invoke.Models.Amendments_Interface_VM

@
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";


<h2>Index</h2>

<div class="panel-group" id="MainScreen">

<div class="panel panel-default">
<div class="panel-heading">
<a data-toggle="collapse" data-parent="#MainScreen" href="#collapse1"><strong>Policy Holder/s</strong></a>
</div>
</div>
<div id="collapse1" class="panel-collapse collapse in">
<div class="panel-body">
<table class="table table-bordered">
<tr>
<th>
@Html.DisplayNameFor(model => model.PolicyNumber)
</th>
<td>
@Html.DisplayFor(model => Model.PolicyNumber)
</td>
<th>
@Html.DisplayNameFor(model => model.DOC)
</th>
<td>
@Html.DisplayFor(model => Model.DOC)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.fkLifeInsured)
</th>
<td>
@Html.DisplayFor(model => Model.fkLifeInsured)
</td>
<th>
@Html.DisplayNameFor(model => model.PolicyStatus)
</th>
<td>
@Html.DisplayFor(model => Model.PolicyStatus)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.RelationshipToLifeInsured)
</th>
<td>
@Html.DisplayFor(model => Model.RelationshipToLifeInsured)
</td>
<th>
@Html.DisplayNameFor(model => model.Package)
</th>
<td>
@Html.DisplayFor(model => Model.Package)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<td>
@Html.DisplayFor(model => Model.Name)
</td>
<th>
@Html.DisplayNameFor(model => model.ContactNumber)
</th>
<td>
@Html.DisplayFor(model => Model.ContactNumber)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.ID_Reg_Num)
</th>
<td>
@Html.DisplayFor(model => Model.ID_Reg_Num)
</td>
<th>
@Html.DisplayNameFor(model => model.EmailAddress)
</th>
<td>
@Html.DisplayFor(model => Model.EmailAddress)
</td>
</tr>
<tr>
</tr>
</table>
</div>
</div>



<div class="panel panel-default">
<div class="panel-heading">
<a data-toggle="collapse" data-parent="#MainScreen" href="#collapse2"><strong>Life Insured</strong></a>
<h3 class="panel-title">
@using (Html.BeginForm("Index", "LifePol", FormMethod.Get))

<p style="padding-left:700px;">
Policy Number: @Html.TextBox("pklifeinsured")
<input type="submit" value="Search" />
</p>

</h3>
</div>
</div>
<div id="collapse2" class="panel-collapse collapse in">
<div class="panel-body">
<table class="table table-bordered">
<tr>
<th>
@Html.DisplayNameFor(model => model.Surname)
</th>
<td>
@Html.DisplayFor(model => Model.Surname)
</td>
<th>
@Html.DisplayNameFor(model => model.fkGender)
</th>
<td>
@Html.DisplayFor(model => Model.fkGender)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<td>
@Html.DisplayFor(model => Model.FirstName)
</td>
<th>
@Html.DisplayNameFor(model => model.fkSmokerStatus)
</th>
<td>
@Html.DisplayFor(model => Model.fkSmokerStatus)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.fkTitle)
</th>
<td>
@Html.DisplayFor(model => Model.fkTitle)
</td>
<th>
@Html.DisplayNameFor(model => model.DateOfBirth)
</th>
<td>
@Html.DisplayFor(model => Model.DateOfBirth)
</td>
</tr>
<tr>
<th>
@Html.DisplayNameFor(model => model.IdNumber)
</th>
<td>
@Html.DisplayFor(model => Model.IdNumber)
</td>
<th>
@Html.DisplayNameFor(model => model.Mobile)
</th>
<td>
@Html.DisplayFor(model => Model.Mobile)
</td>
</tr>
<tr>
</tr>
</table>
</div>
</div>
</div>


public Amendments_Interface_VM HttpClientCall(Amendments_Interface_VM value, string uri, int? pklifeinsured)

var client = new HttpClient BaseAddress = new Uri(apiURL) ;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var httpresult = client.GetAsync(apiURL).Result;

if(httpresult.IsSuccessStatusCode)

var result = httpresult.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<Amendments_Interface_VM>(result);
return data;


return new Amendments_Interface_VM();



error






Hey matey and welcome to SO! :) Can you add your code into the question? Images make it hard to try and figure out whats going on :)

– garfbradaz
Sep 12 '18 at 7:57






Hi @garfbradaz, I have included the code as well.

– ZUKISA BHOLOSHA
Sep 12 '18 at 8:24




2 Answers
2



You can have the Policies property in you Person model and have it populated with necessary operation. Your model should look something like this. You can return all related entities by having entity property in the model.


public class Person

/* public int Id get; set;
* Other properties
*/

public List<PolicyHolderVM> policiesLst get; set;



I have created function to call the API. This will return the Person object coming from the API.


public Person HttpClientCall(Person value, string uri)

var client = new HttpClient BaseAddress = new Uri(_baseUrl) ;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var httpresult = client.GetAsync(uri).Result;

if (httpresult.IsSuccessStatusCode)

var result = httpresult.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<Person>(result);
return data


return new Person();






Hi @Aunell, I am already doing this in my WebApi project and it works fine.. Now I am calling the WebApi project in a separate MVC project which is not connected to the database, so I need a ViewModel to pass all the data coming from the WebApi, and show it in a MVC cshtml view.

– ZUKISA BHOLOSHA
Sep 12 '18 at 7:53






Hi @Auneell please see my code above, I hope this will give you better information regarding my question

– ZUKISA BHOLOSHA
Sep 12 '18 at 8:31






@ZUKISABHOLOSHA You need to have the same class structure at you MVC project. API will return your data in JSON format so convert JSON to your object using NewtonSoft package like this for example "Movie m = JsonConvert.DeserializeObject<Movie>(json);"

– Auneell
Sep 12 '18 at 10:13







I'm not sure where the above code would go. Is it in my view or the mvc controller. Can you kindly give an example based on the above code structure.... The reason I'm asking is because the application returns the Person data to my mvc view, but not the Policy information.

– ZUKISA BHOLOSHA
Sep 12 '18 at 10:19






@ZUKISABHOLOSHA I have updated my answer. Please have a look and let me know if that works for you or not.

– Auneell
Sep 12 '18 at 10:32




I think you can create a model as below in your mvc application and then call the api


public class YourModel

public Person Personget;set;
public List<Policy> Policies get;set;



and then make webapi method to send data in the same format as that of model, or you can even use thissame model in webapi for sending data.



now in your webapi controller:


YourModel data=new YourModel();
Person person=new Person();
person.name="test name";
.
.
data.Person=person;
Policy policy1=new Policy();
policy1.name="test name";
.
.
Policy policy2=new Policy();
policy2.name="test name 2";
.
.
data.Policies.Add(policy1);
data.Policies.Add(policy2);

return Ok(data);



hope it helps :)



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ