简体   繁体   中英

How to pass data from Mvc Controller to WebApi Controller?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM