question

MikoKage avatar image
0 Votes"
MikoKage asked MikoKage commented

How can I implement an API Server with MVC

Got the solution

dotnet-csharpdotnet-aspnet-mvcdotnet-aspnet-webapi
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Also, my Connection String:
<connectionStrings>
<add connectionString="EnterYourConnectionStringHere" name="defaultConnection" providerName="System.Data.SqlClient" />
</connectionStrings>

in Web.config.
Hope I did that one right

0 Votes 0 ·
YijingSun-MSFT avatar image
1 Vote"
YijingSun-MSFT answered

Hi @MikoKage ,
According to your codes,I know that you are doing CRUD operations. Now,you need to interact with the data/information you expose to them.
You need to use jquery ajax to implement it.

Best regards,
Yijing Sun


If the answer is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Doxchan-6070 avatar image
0 Votes"
Doxchan-6070 answered Doxchan-6070 commented

Hey,
for the ViewController to work, you need an ApiController
It should look like this...

 public class storesController : ApiController
     {
         private BikeStoreEntities db = new BikeStoreEntities();
    
         // GET: api/stores
         public IHttpActionResult Getstores()
         {
             var stores = db.stores.Select(s => new StoreDTO() { 
                 store_id = s.store_id,
                 store_name = s.store_name,
                 street = s.street,
                 city = s.city,
                 email = s.email
             });
    
             return Ok(stores);
         }
    
         // GET: api/stores/5
         [ResponseType(typeof(StoreDTO))]
         public IHttpActionResult Getstores(int id)
         {
             stores store = db.stores.Find(id);
             StoreDTO dto = new StoreDTO
             {
                 store_id = store.store_id,
                 store_name = store.store_name,
                 street = store.street,
                 city = store.city,
                 email = store.email
             };
             if (store == null)
             {
                 return NotFound();
             }
    
             return Ok(dto);
         }
    
         // PUT: api/stores/5
         [ResponseType(typeof(void))]
         public IHttpActionResult Putstores(StoreDTO store)
         {
             if (!ModelState.IsValid)
             {
                 return BadRequest(ModelState);
             }
    
                
             stores stores1 = new stores
             {
                 store_id = store.store_id,
                 store_name = store.store_name,
                 street = store.street,
                 city = store.city,
                 email = store.email
             };
    
             db.Entry(stores1).State = EntityState.Modified;
    
             try
             {
                 db.SaveChanges();
             }
             catch (DbUpdateConcurrencyException)
             {
                 if (!storesExists(store.store_id))
                 {
                     return NotFound();
                 }
                 else
                 {
                     throw;
                 }
             }
    
             return StatusCode(HttpStatusCode.NoContent);
         }
    
         // POST: api/stores
         [ResponseType(typeof(stores))]
         public IHttpActionResult Poststores(StoreDTO store)
         {
             if (!ModelState.IsValid)
             {
                 return BadRequest(ModelState);
             }
             stores stores1 = new stores
             {
                 store_id = store.store_id,
                 store_name = store.store_name,
                 street = store.street,
                 city = store.city,
                 email = store.email
             };
             db.stores.Add(stores1);
             db.SaveChanges();
    
             return CreatedAtRoute("DefaultApi", new { id = store.store_id }, store);
         }
    
         // DELETE: api/stores/5
         [ResponseType(typeof(StoreDTO))]
         public IHttpActionResult Deletestores(int id)
         {
             stores stores = db.stores.Find(id);
             if (stores == null)
             {
                 return NotFound();
             }
    
             StoreDTO dto = new StoreDTO
             {
                 store_id = stores.store_id,
                 store_name = stores.store_name,
                 street = stores.street,
                 city = stores.city,
                 email = stores.email
             };
    
             db.stores.Remove(stores);
             db.SaveChanges();
    
             return Ok(stores);
         }
    
         protected override void Dispose(bool disposing)
         {
             if (disposing)
             {
                 db.Dispose();
             }
             base.Dispose(disposing);
         }
    
         private bool storesExists(int id)
         {
             return db.stores.Count(e => e.store_id == id) > 0;
         }
     }



· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

public class BookStoreContext : DbContext
{
public BookStoreContext() : base("DefaultConnection") {
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BookStoreContext, CFAPI.Migrations.Configuration>());
}

     public DbSet<Books> books { get; set; }
     public DbSet<Authors> authors { get; set; }
     public DbSet<BookStores> bookStores { get; set; }
 }


0 Votes 0 ·

Enable-Migrations
add-migration (name)
update-database -verbose

0 Votes 0 ·
Doxchan-6070 avatar image
0 Votes"
Doxchan-6070 answered

public class StoreViewController : Controller
{
HttpClient client = new HttpClient();
// GET: StoreView
public ActionResult Index()
{
IEnumerable<StoreDTO> stores = null;

         client.BaseAddress = new Uri("http://localhost:53739/api/");
         var responseTask = client.GetAsync("stores");
         responseTask.Wait();
         var result = responseTask.Result;
         if (result.IsSuccessStatusCode)
         {
             var readTask = result.Content.ReadAsAsync<IList<StoreDTO>>();
             stores = readTask.Result;
         }

         return View(stores);
     }

     // GET: StoreView/Details/5
     public ActionResult Details(int id)
     {
         StoreDTO store = null;
         client.BaseAddress = new Uri("http://localhost:53739/api/");
         var responseTask = client.GetAsync("stores?id="+id);
         responseTask.Wait();
         var result = responseTask.Result;
         if (result.IsSuccessStatusCode)
         {
             var readTask = result.Content.ReadAsAsync<StoreDTO>();
             store = readTask.Result;
         }
         return View(store);
     }

     // GET: StoreView/Create
     public ActionResult Create()
     {
         return View();
     }

     // POST: StoreView/Create
     [HttpPost]
     public ActionResult Create(FormCollection collection, StoreDTO store)
     {
         client.BaseAddress = new Uri("http://localhost:53739/api/stores");
         var postTask = client.PostAsJsonAsync("stores", store);
         postTask.Wait();
         var result = postTask.Result;
         if (result.IsSuccessStatusCode)
         {
             return RedirectToAction("Index");
         }
         return View();
     }

     // GET: StoreView/Edit/5
     public ActionResult Edit(int id)
     {
         StoreDTO store = null;
         client.BaseAddress = new Uri("http://localhost:53739/api/");
         var responseTask = client.GetAsync("stores?id=" + id);
         responseTask.Wait();
         var result = responseTask.Result;
         if (result.IsSuccessStatusCode)
         {
             var readTask = result.Content.ReadAsAsync<StoreDTO>();
             store = readTask.Result;
         }
         return View(store);
     }

     // POST: StoreView/Edit/5
     [HttpPost]
     public ActionResult Edit(FormCollection collection, StoreDTO store)
     {
         client.BaseAddress = new Uri("http://localhost:53739/api/stores");
         var putTask = client.PutAsJsonAsync("stores", store);
         putTask.Wait();
         var result = putTask.Result;
         if (result.IsSuccessStatusCode)
         {
             return RedirectToAction("Index");
         }
         return View(store);
     }

     // GET: StoreView/Delete/5
     public ActionResult Delete(int id)
     {
         StoreDTO store = null;
         client.BaseAddress = new Uri("http://localhost:53739/api/");
         var responseTask = client.GetAsync("stores?id=" + id);
         responseTask.Wait();
         var result = responseTask.Result;
         if (result.IsSuccessStatusCode)
         {
             var readTask = result.Content.ReadAsAsync<StoreDTO>();
             store = readTask.Result;
         }
         return View(store);
     }

     // POST: StoreView/Delete/5
     [HttpPost]
     public ActionResult Delete(int id, FormCollection collection)
     {
         client.BaseAddress = new Uri("http://localhost:53739/api/");
         var deleteTask = client.DeleteAsync("stores?id="+id);
         deleteTask.Wait();
         var result = deleteTask.Result;
         if (result.IsSuccessStatusCode)
         {
             return RedirectToAction("Index");
         }
         return View(id);
     }
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Doxchan-6070 avatar image
0 Votes"
Doxchan-6070 answered

This can be useful aswell
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using TestUe.Models;

 namespace TestUe.Controllers
 {
     public class stocksController : ApiController
     {
         private CompanyEntities db = new CompanyEntities();
    
         // GET: api/stocks
         public IHttpActionResult Getstocks(int sid)
         {
             var stocks = db.stocks.Include("products").Where(s => s.store_id == sid).Select(s => new StocksDTO()
             {
                 store_id = s.store_id,
                 product_id = s.product_id,
                 quantity = s.quantity,
                 product_name = s.products.product_name,
             });
             return Ok(stocks);
         }
    
         // GET: api/stocks/5
         [ResponseType(typeof(StocksDTO))]
         public IHttpActionResult Getonestocks(int sId, int pId)
         {
             stocks stocks = db.stocks.Find(sId, pId);
             StocksDTO stdto = new StocksDTO()
             {
                 store_id = stocks.store_id,
                 product_id = stocks.product_id,
                 quantity = stocks.quantity,
                 product_name = stocks.products.product_name
             };
             if (stocks == null)
             {
                 return NotFound();
             }
    
             return Ok(stdto);
         }
    
         // PUT: api/stocks/5
         [ResponseType(typeof(void))]
         public IHttpActionResult Putstocks(StocksDTO stocks)
         {
             if (!ModelState.IsValid)
             {
                 return BadRequest(ModelState);
             }
    
             stocks st = new stocks()
             {
                 store_id = stocks.store_id,
                 product_id = stocks.product_id,
                 quantity = stocks.quantity
             };
             db.Entry(st).State = EntityState.Modified;
    
             try
             {
                 db.SaveChanges();
             }
             catch (DbUpdateConcurrencyException)
             {
                 if (!stocksExists(stocks.product_id, stocks.store_id))
                 {
                     return NotFound();
                 }
                 else
                 {
                     throw;
                 }
             }
    
             return StatusCode(HttpStatusCode.NoContent);
         }
    
         // POST: api/stocks
         [ResponseType(typeof(StocksDTO))]
         public IHttpActionResult Poststocks(StocksDTO stocks)
         {
             if (!ModelState.IsValid)
             {
                 return BadRequest(ModelState);
             }
    
             stocks st = new stocks()
             {
                 store_id = stocks.store_id,
                 product_id = stocks.product_id,
                 quantity = stocks.quantity
             };
             db.stocks.Add(st);
    
             try
             {
                 db.SaveChanges();
             }
             catch (DbUpdateException)
             {
                 if (stocksExists(stocks.store_id, stocks.product_id))
                 {
                     return Conflict();
                 }
                 else
                 {
                     throw;
                 }
             }
    
             return CreatedAtRoute("DefaultApi", new { id = stocks.store_id }, stocks);
         }
    
         // DELETE: api/stocks/5
         [ResponseType(typeof(StocksDTO))]
         public IHttpActionResult Deletestocks(int sId, int pId)
         {
             stocks stocks = db.stocks.Find(sId, pId);
             if (stocks == null)
             {
                 return NotFound();
             }
             StocksDTO stdto = new StocksDTO()
             {
                 store_id = stocks.store_id,
                 product_id = stocks.product_id,
                 quantity = stocks.quantity,
                 product_name = stocks.products.product_name
             };
             db.stocks.Remove(stocks);
             db.SaveChanges();
    
             return Ok(stdto);
         }
    
         protected override void Dispose(bool disposing)
         {
             if (disposing)
             {
                 db.Dispose();
             }
             base.Dispose(disposing);
         }
    
         private bool stocksExists(int pId, int sId)
         {
             return db.stocks.Count(e => e.store_id == sId && e.product_id == pId) > 0;
         }
     }
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.