0

Before marking this as a duplicate guys, I've already checked these questions

Passing data from a WebApi Controller to an MVC Controller

ASP.Net MVC How to pass data from view to controller

I'm trying to get into the asp.net WebApi world after working with MVC for like 6 months, but still I don't know when and what is the proper way to use WebApi with a normal MVC application. If someone know any good documentation or some good tutorials it would be so appreciated.

Any way I'm trying to make an MVC app with WebAPI, I have a solution that contains 2 projects "mvcApplication" and "myWebApiApplication". I ran the solution for both projects, and I tested a GET request like this and it worked:

MVC Index Controller

public ActionResult Index()
{
    IEnumerable<mvcStudentModel> empList;
    HttpResponseMessage response = GlobalVariables.webApiClient.GetAsync("Students").Result;
    empList = response.Content.ReadAsAsync<IEnumerable<mvcStudentModel>>().Result;
    return View(empList);
}

WebAPi controller

public class StudentsController : ApiController
{
    private StudentsDBEntities db = new StudentsDBEntities();

    // GET: api/Students
    [Route("api/Studentst")]
    [HttpGet]
    public IQueryable<Student> Students()
    {
        return db.Students;
    }

I then added a ListView template, and everything is working fine.

Now I don't know if I'm doing this correctly , but I tried to insert a new student to the Students Table(ID,Name).

So I tried to add in the index view 1 textfield with a submit button.

@Html.BeginForm("AddStudent", "Index"){ 
    <input type="text" name="username" placeholder="Student name" />
    <button type="submit" class="btn btn-warning">
}

When I hit the submit button it fires the "AddStudent" method controller:

public  ActionResult isAvailable(string username)
{
    // What code should I put here to pass data to WebApi
}

And let's suppose I can call the WebApi method with a POST request to add the student, I added this to my WebApi controller:

[Route("api/AddNewStudent")]
[HttpPost]
public IQueryable<Student> check(string name)
{
    var test = db.Students.Where(a => a.StudentName.Equals(name)).FirstOrDefault();
    if (test!=null)
    {
        // add Student code
    }
}

But after that I don't know what to do (I mean first I want to pass the data from the MVC controller to the WebApi controller, to add the student in the WebApi controller), and I've created a StudentModel for passing the data if needed.

Sorry for the long question, and thanks for any help.

4
  • tutorialsteacher.com/webapi/… here you can find good example. Commented Mar 11, 2019 at 14:44
  • Is the WebApi controller in the same Project as the MVC Controller? Commented Mar 11, 2019 at 15:24
  • No @ErikPhilips , but it is in the same solution Commented Mar 12, 2019 at 13:59
  • Is the WebApi controller in the same Project as the MVC Controller? Commented Mar 12, 2019 at 14:40

1 Answer 1

0

Well there are more than one answers for this question. Why do you want to call Web API from MVC Application? Are they both part of different solutions or they belong to same solution?

string apiUrl = "http://localhost:12408/api/Studentst";

            using (HttpClient client=new HttpClient())
        {
            client.BaseAddress = new Uri(apiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new 
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync(apiUrl);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsStringAsync();
                var student = 
Newtonsoft.Json.JsonConvert.DeserializeObject<[QualifiedNamespace].Student>(data);
            }
        }

One of the simplest tutorial to start with: https://www.tutorialsteacher.com/webapi/consume-web-api-get-method-in-aspnet-mvc

I'd always refer to MSDN documentation, as it will have latest and most accurate infomration.

Sign up to request clarification or add additional context in comments.

1 Comment

If the AOI I am calling from the MVC applciation is only used in this application only I'd preferabily move the code to MVC controller itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.