I have 2 tables(student and parent) into which I wanna post the data. I have a MVC controller and an API controller. I am trying to route createStudent(StudentViewModel student) action method in mvc controller to PostStudent(StudentViewModel student) in API controller and createParent(ParentViewModel p) to PostParent(ParentViewModel p) respectively. But having two post methods in API controller makes it ambiguous.
I am not able to find a way to use two post methods in same api controller through mvc controller.
This is my code in MVC Controller(named StudentController)
public ActionResult createStudent()
{
return View();
}
[System.Web.Mvc.HttpPost]
public ActionResult createStudent(StudentViewModel student)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:39673/api/student");
var postTask = client.PostAsJsonAsync<StudentViewModel>("student", student);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(student);
}
public ActionResult createparent()
{
return View();
}
[System.Web.Mvc.HttpPost]
public ActionResult createparent(ParentViewModel p)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:39673/api/Student");
//HTTP POST
var postTask = client.PostAsJsonAsync<ParentViewModel>("parent", p);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return View();
}
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(p);
}
This is my API Controller(named StudentController)
public class StudentController : ApiController
{
//POST Student
public IHttpActionResult PostStudent(StudentViewModel student)
{
if (!ModelState.IsValid)
return BadRequest("Invalid data.");
using (var ctx = new MyEntities())
{
ctx.Students.Add(new Student()
{
Name = student.Name,
MobileNO = student.MobileNO
});
ctx.SaveChanges();
}
return Ok();
}
//POST Parent
public IHttpActionResult PostParent(ParentViewModel p)
{
if (!ModelState.IsValid)
return BadRequest("Invalid data.");
using (var ctx = new MyEntities())
{
ctx.Parents.Add(new Parent()
{
StudentID=p.StudentID,
ParentName = p.ParentName,
});
ctx.SaveChanges();
}
return Ok();
}
}
Thanks