j-s j-s - 1 month ago 13
reST (reStructuredText) Question

Sending data through web service to databse in ASP.net MVC

Under one colution file I have couple of projects.UI (ASP.Net mvc) project, A project for my rest services, A DTO project, A business logic project and Data Access. Now my services projects's controller needs to talk with my UI(ASP.Net MVC) project's controller and get the data entered in the form and send it to the database. Im quite unsure of the logic I should come up with inside the controller class of the UI project. The UI project sepratley has entity classes as well. Help needed!!

This is the POST method in my services controller

// POST api/Maintenance
[HttpPost]
public IHttpActionResult Post([FromBody]Maintenance maintenance)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
maintenanceLogic.Insert(maintenance);

return CreatedAtRoute("DefaultApi", new { id = maintenance.WorkID }, maintenance);
}


This is the method that will access the above methods uri.This method is in the controller class of my UI project. I came up with a logic.But I think its not correct.

[HttpPost, Route("/maintenance/CreateMaintenanceOrder")]
public PartialViewResult CreateMaintenanceOrder([FromBody] Maintenance Model)
{
Model.CheckItems = maintenanceViewModel.CheckItems;
Model.CrewMembers = maintenanceViewModel.CrewMembers;
Model.WorkID = ++SessionUtility.CurrentMaintenanceID;
try
{
var uri = "api/Maintenance/Post ";

using (HttpClient httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://localhost:8961");
Task<String> request = httpClient.GetStringAsync(uri);
Model = JsonConvert.DeserializeObject<List<Maintenance>>(request.Result);
}
maintenanceViewModel.MaintenanceOrders.Add(Model);

}
catch (AggregateException e)
{

}

maintenanceViewModel.MaintenanceOrders.Add(Model);
return PartialView("_Search", maintenanceViewModel);
}

Answer

You are trying to call a Post method using GetAsync as well as it seems you are not passing the Maintenance object required by Rest service method as input. Please try below -

string maintenanceData = JsonConvert.SerializeObject(Model); //considering you have to pass Model as input to Rest method
HttpResponseMessage response = httpClient.PostAsync(new Uri("http://localhost:8961" + "api/Maintenance/Post/"), new StringContent(maintenanceData));
Comments