Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
problem

How to convert that code please from mvc project to web API


I work on mvc project in asp.net core 2.1

I create Employee Controller and inside it I make two function action result for create

new employee and save it as following :

I decided to convert above functions to web API so that

How to convert create new employee page or form get and post according to actions above to web API ?

What I have tried:

public IActionResult Create()
        {
           var model = new Employee();
            if (id == null)
            {
                
                model.EmployeeId = _repository.GetAll().Max(Employee => Employee.EmployeeId) + 1;
             }
            return View(model);
        }

      
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                _context.Add(employee);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(employee);
        }
Posted
Updated 16-Feb-19 0:05am

Generally the Web API build is going to be drop-in your existing Models and Controllers with very little code changes. What is going to be different is that APIs do not have a front end.

Your forms are going to be on stand alone web pages or within another project that does have a user interface. From stand-alone web pages you would use AJAX for submission of the form. If it is another server-client project (MVC, Web Forms, etc) you could also programmatically submit the data to the API.

Here is some documentation on how to get started:
Get Started with ASP.NET Web API 2 (C#) | Microsoft Docs[^]
 
Share this answer
 
Comments
ahmed_sa 15-Feb-19 20:41pm    
only one question i make this as web api to connect to angular on client side
so that are create method get must be written in web api or can done from front end
ahmed_sa 15-Feb-19 20:46pm    
and first create function get type that return max record + 1
are this function also will done on web API
if must
How to write it please
MadMyche 16-Feb-19 2:20am    
Create is an action that would be in your API Controller, working through the Model. Your methods within there can return the new identity value and send it back to the front end
As already mentioned in Solution 1, by MadMyche, you cannot simply convert your applications to an API, where API itself is a separate way or method of development of applications. An API has so many requirements, such as being stateless, headless, and cross-platform, and cross-device. APIs work directly on the HTTP protocol, and do not require a browser to display the content. In this fashion, the Views etc won't be needed.

Representational state transfer - Wikipedia[^]

This way, you would be using a data-interchange format, like JSON or XML, and then return the data using these formats, and then access that from the client. So here is the thing, you need to change the View to the Models—you return the data instead of an HTML document. Then that data can be accessed anywhere, and parsed.

Please see this article of mine to understand how this can happen, ASP.NET 5 Web API RESTful CRUDs and Windows 10 native application[^]

Your code, would be changed to the following code,
// Change from IActionResult to the data, this will be serialized to JSON (or XML)
[HttpPost]
public Employee Create()
{
    var model = new Employee();
    if (id == null)
    {
        
        model.EmployeeId = _repository.GetAll().Max(Employee => Employee.EmployeeId) + 1;
    }

    // Return the data itself, not the View
    return model;
}

// You can do the same "async" thing using API too, just return the data
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<Employee> Create(Employee employee)
{
    // See below for more ways to capture, bind and validate the model values.
    _context.Add(employee);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));

    // Return the data again
    return employee;
}
Here is another interesting thing, since you are using an API, your users can upload the data using any method, query string, POST it via HTTP body, send a file, send as form-data, whatever. You need to check the data via those methods, such as [FromBody], etc.

Model Binding in ASP.NET Core | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900