angular Js with Code first approch using WEB API and SPA - angularjs

WE are using SPA template,Code first Approach(Entity Framework),Web API for services and Angular.js for DataBind.We are able to connect with our database to perform the CRUD aperation.But the Problem is that data is not displaying in the Web Page.Below is the code snippet:
Markup Script:-
<table id="example" class="table table-bordered table-hover" style="border:1px solid lightgray">
<thead>
<tr>
<th>ProgramID</th>
<th>ProgramName</th>
<th>SiteID</th>
</tr>
</thead>
<tbody id="tableBody">
<tr data-ng-show="addMode">
<td></td>
<td><input type="text" data-ng-model="newStatusDTO.ProgramID" /></td>
<td><input type="text" data-ng-model="newStatusDTO.ProgramName" /></td>
<td><input type="text" data-ng-model="newStatusDTO.SiteID" /></td>
<td>
<p><a data-ng-click="add(newStatusDTO)" href="javascript:;">Save</a> | <a data-ng-click="toggleAdd()" href="javascript:;">Cancel</a></p>
</td>
</tr>
<tr data-ng-repeat="StatusD in sgvm.gridData">
<td data-ng-model="StatusD.ProgramName">{{StatusD.ProgramName}}</td>
<td>
<p data-ng-hide="StatusD.editMode">{{ StatusD.ProgramName }}</p>
<input data-ng-show="StatusD.editMode" type="text" data-ng-model="StatusD.ProgramName" />
</td>
<td>
<p data-ng-hide="StatusD.editMode">{{ StatusD.SiteID }}</p>
<input data-ng-show="StatusD.editMode" type="text" data-ng-model="StatusD.SiteID" />
</td>
<td>
<p data-ng-hide="StatusD.editMode"><a data-ng-click="toggleEdit(StatusD)" href="javascript:;">Edit</a> | <a data-ng-click="deleteStatusDTO(StatusD)" href="javascript:;">Delete</a></p>
<p data-ng-show="StatusD.editMode"><a data-ng-click="save(StatusD)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(StatusD)" href="javascript:;">Cancel</a></p>
</td>
</tr>
</tbody>
</table>
Angular Code:
angular.module('PPCRApp', [
'PPCRSearchController'
]);
function PPCRSearchController($scope, $http) {
$scope.loading = true;
$scope.addMode = false;
//Used to display the data  
$http.get('/api/PPCRSearch/GetProgram').success(function(data) {
$scope.sgvm = data;
$scope.loading = false;
})
.error(function() {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
$scope.toggleEdit = function() {
this.StatusD.editMode = !this.StatusD.editMode;
};
$scope.toggleAdd = function() {
$scope.addMode = !$scope.addMode;
};
//Used to save a record after edit  
$scope.save = function() {
$scope.loading = true;
var abc = this.StatusD;
$http.put('/api/PPCRSearch/UpdateStatus/', abc).success(function(data) {
alert("Saved Successfully!!");
abc.editMode = false;
$scope.loading = false;
}).error(function(data) {
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
//Used to add a new record  
$scope.add = function() {
$scope.loading = true;
$http.post('/api/PPCRSearch/PostStatus/', this.newStatusDTO).success(function(data) {
alert("Added Successfully!!");
$scope.addMode = false;
$scope.sgvm.gridData.push(data);
$scope.loading = false;
}).error(function(data) {
$scope.error = "An Error has occured while Adding Friend! " + data;
$scope.loading = false;
});
};
//Used to edit a record  
$scope.deleteStatusDTO = function() {
debugger;
$scope.loading = true;
var prgid = this.StatusD.programID;
$http.delete('/api/PPCRSearch/DeleteProgram/' + prgid).success(function(data) {
debugger;
alert("Deleted Successfully!!");
$.each($scope.sgvm.gridData, function(i) {
if ($scope.sgvm.gridData[i].programID == prgid) {
$scope.sgvm.gridData.splice(i, 1);
return false;
}
});
$scope.loading = false;
}).error(function(err) {
debugger;
$scope.error = "An Error has occured while deleting Friend! " + err.val();
$scope.loading = false;
});
};
}
GetProgram Function:
public class PPCRSearchController: ApiController {
private DataContext db = new DataContext();
static readonly IPPCRRepository repository = new ProgramRepository();
[HttpGet]
public SearchGridViewModel GetProgram() {
var b = repository.GetProgram(1, 10);
return b;
}
}
ProgramRepository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SPAwithAngular.Models {
public class ProgramRepository: IPPCRRepository {
public SearchGridViewModel GetProgram(int page, int pagesize) {
using(DataContext dbcontext = new DataContext()) {
SearchGridViewModel ddl = new SearchGridViewModel();
var lstProgram = from r in dbcontext.Program select r;
var a = Converter.LProgramDTO(lstProgram.ToList());
ddl.gridData = (0 == page ? null : a.Skip((page - 1) * pagesize).Take(pagesize).ToList());
// calculated number of pages and ceil the value
ddl.NumberOfPages = ((int) Math.Ceiling((double) a.Count / pagesize));
return ddl;
}
}
}
}
SearchGridViewModel function:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SPAwithAngular.Models {
public class SearchGridViewModel {
public List < ProgramDTO > gridData {
get;
set;
}
public int NumberOfPages {
get;
set;
}
}
}
ProgramDTO:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SPAwithAngular.Models {
public class ProgramDTO {
public int ProgramID {
get;
set;
}
public string ProgramName {
get;
set;
}
public int SiteID {
get;
set;
}
}
}
The records are saved successfully in database.But while trying to fetch it is not displayed.

Related

POST dynamically added Lists to Controller as Json and redirect view

Description
I'm am creating a dynamic table where the user can select regions in a dropdown lists. On "add" the user can also add new table rows with region dropdown lists included. On POST, a list of Regions should be posted to the controller where it´s being saved to the SavingPlan model.
Problem
Ajax is returning null to my controller even though I have saved selected option-data to string arrays which is being posted to the controller.
Addition
I am fairly new to ASP.NET MVC so please have that in mind when commenting. I am open minded towards doing things differently but I´d very much appreciate I someone would be able to guid me and my code in the right direction.
Region Model
public class Region
{
public int Id { get; set; }
public string Name { get; set; }
}
Saving Plan Model
public SavingPlan()
{
}
public SavingPlan(List<Region> regionList)
{
RegionList = regionList;
}
public int Id { get; set; }
public ApplicationUser AssessmentUser { get; set; }
public IEnumerable<Region> RegionLookUp { get; set; }
public bool IsActive { get; set; }
public byte RegionId { get; set; }
public Region Region { get; set; }
public List<Region> RegionList { get; set; }
}
SavingPlan - ViewModel
public class SavingPlan
{
public SavingPlan()
{
}
public SavingPlan(List<Region> regionList)
{
RegionList = regionList;
}
public int Id { get; set; }
public ApplicationUser AssessmentUser { get; set; }
public IEnumerable<Region> RegionLookUp { get; set; }
public bool IsActive { get; set; }
public byte RegionId { get; set; }
public Region Region { get; set; }
public List<Region> RegionList { get; set; }
}
Controller Action GET - NewSavingPlan
public ActionResult NewSavingPlan()
{
SavingPlanAssessmentView viewModel = new SavingPlanAssessmentView();
viewModel.SavingPlan = new SavingPlan();
var regions = _context.Regions
.ToList();
viewModel.RegionLookUp = regions;
return View(viewModel);
}
Controller Action POST - Save SavingPlan
[HttpPost]
public JsonResult SaveList(string RegionList)
{
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Assessments");
string[] arr = RegionList.Split(',');
foreach (var item in arr)
{
var region = item;
}
return Json(new { status = "success", redirectUrl = Url.Action("Index","Home") });
}
SavingPlan Partial View
#model BBRG.ViewModels.SavingPlanAssessmentView
<h2>#Model.Heading</h2>
#*#using (Html.BeginForm("Save", "Assessments", FormMethod.Post))
{*#
#*#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)*#
<legend>Saving Plan</legend>
<table id="regionTable" class="table table-striped">
<thead>
<tr>
<td>Region</td>
<td> <button id="add" type="button" class="btn btn-link">Add</button></td>
<td></td>
</tr>
</thead>
<tbody>
<tr id="regionRow_1">
<td>
#Html.DropDownListFor(m => m.RegionId, new SelectList(Model.RegionLookUp, "Id", "Name"), "Select Region", new { #class = "form-control Region", id = "Region_1", type="string", name = "Region", selected="false" })
</td>
<td>
<button data-region-id="#Model.RegionId" id="deleteRegion" type="button" class="btn btnDeleteRegion btn-link btn-xs btn" btn-xs>remove</button>
</td>
</tr>
</tbody>
</table>
<hr />
<p>
#Html.HiddenFor(m => m.Id)
<button data-saving-id="#User.Identity" onclick="saveRegion()" type="submit" calss="btn btn-default js-toggle-save">Save</button>
</p>
Jquery - Add new table row with dropdownlist
$(document).ready(function () {
var counter = 2;
$(function () {
$('#add').click(function () {
$('<tr id="regionRow_' + counter + '">'
+ '<td>'
+ '<select type="text" value="RegionId" name="Region" id="Region_'+ counter+'" class="form-control Region" " >'
+ $(".Region").html()
+ '</select>'
+ '</td>'
+ '<td>'
+ '<button data-region-id= id="deleteRegion" type="button" class="btn btnDeleteRegion btn-link btn-xs btn" btn-xs>remove</button>'
+ '</td>'
+ '</tr>').appendTo('#regionTable');
counter++;
return false;
});
});
});
Jquery and .ajax for POST
{
<script src="~/Scripts/SavingPlanScripts.js"></script>
<script>
var saveRegion = (function () {
var array = [];
var commaSeperated = "";
var count = 1;
$("#regionTable tbody .Region").each(function (index, val) {
var regionId = $(val).attr("Id");
var arr = regionId.split('_');
var currentRegionId = arr[1];
var isSelected = $(".Region option").is(':selected', true);
if (isSelected) {
array.push(currentRegionId);
}
count++;
});
if (array.length != 0) {
commaSeperated = array.toString();
$.ajax({
type: "POST",
dataType: "json",
contentType: "/application/json",
url: "/SavingPlans/SaveList",
data: { "RegionList": commaSeperated },
success: function (json) {
if (json.status == "success") {
window.location.href = json.redirectUrl;
};
}
});
};
});
</script>
}```
I found the solution to my problem, I forgot to stringify my .ajax data. If anyone still want to provide me with some constructive input, please don´t hesitate.
$.ajax({
url: "../SavingPlans/SaveList",
data: JSON.stringify({ RegionId: commaSeperated }),
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (json) {
if (json.status == "success") {
window.location.href = json.redirectUrl;
};
}
});

Angularjs returnJson from database

I want to return a JSON Object in a datatable. I've provided the static working code that I found in an example in my angularjs template.
Thanks for help.
controller.js
function datatablesCtrl($scope,DTOptionsBuilder){
$scope.persons = [
{
id: '1',
firstName: 'Monica',
lastName: 'Smith'
},
{
id: '2',
firstName: 'Sandra',
lastName: 'Jackson'
}
];
}
Utenti.jsp
<div class="wrapper wrapper-content animated fadeInRight" ng-controller="datatablesCtrl">
<div class="row">
<div class="col-lg-12">
<table datatable="ng" dt-options="dtOptions" class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in persons">
<td>{{ person.id }}</td>
<td>{{ person.user }}</td>
<td>{{ person.password }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I need to populate the $scope.person with data into a database.
The table of database is "utenti" with column id,fistName,lastName.
These are my classes.. There is also a class Utenti with a simple getter & setter.
UtentiService.class
#Service("UtentiService")
public class UtentiService implements IUtentiService{
private EntityManager entityManager;
final static Logger logger = Logger.getRootLogger();
#PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
#Transactional(readOnly = true)
public List<Utenti> getAll() {
Query queryFindAll = null;
try{
queryFindAll = entityManager.createNamedQuery("utenti.findAll");
}catch(Exception ex){
logger.error("Failed in method **getAll** of utentiService: ",ex);
}
return (List)queryFindAll.getResultList();
}
}
IUtentiService.class
public interface IUtentiService {
public List<Utenti> getAll(); //Restituisce una lista di tutti i siti
}
UtentiRest.class
#Path("/utenti")
#Component
#Scope("request")
public class UtentiRest {
#Autowired
IUtentiService nameUtentiService;
final static Logger logger = Logger.getRootLogger();
#GET
#Produces("application/json")
#Path("/getAll")
public JSONObject getAll() {
ExecutorService executorService = Executors.newFixedThreadPool(10);
JSONObject jsonSitiTotal = new JSONObject();
try {
List<Utenti> soluzioni = nameUtentiService.getAll();
Iterator<Utenti> iter = soluzioni.iterator();
JSONArray jsonArray = new JSONArray();
while (iter.hasNext()) {
Utenti ut = (Utenti) iter.next();
JSONObject jsonSiti2 = new JSONObject();
jsonSiti2.put("id", ut.getId());
jsonSiti2.put("user", ut.getUserName());
jsonSiti2.put("password", ut.getPassword());
jsonArray.put(jsonSiti2);
}
jsonSitiTotal.put("Siti",jsonArray);
} catch (JSONException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.BAD_REQUEST)
.entity("JSON Exception " + ex.getMessage())
.build()
);
} catch (NullPointerException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.NO_CONTENT)
.entity("No process find ")
.build()
);
} catch (IllegalArgumentException ex) {
logger.info(Level.ERROR, ex);
throw new WebApplicationException(
Response.status(Response.Status.NOT_ACCEPTABLE)
.entity("Couldn't process request with the provided argument: "
+ " (" + ex.getMessage() + ")")
.build()
);
}finally {
executorService.shutdown();
}
return jsonSitiTotal;
}
}

AngularJs - Fill table with $resource

I'm learning angularjs and I'm triyng to get a list of Object from WebApi. I've already tried to do it with $ http and it works fine:
// in controller
var listC = 'http://localhost:12345/api/WebApiTest/ContList';
$http({
method: 'GET', url: listC
}).success(function (ContactsList) {
$scope.contacts= ContactsList;
}).error(function () {
alert("Error in List");
});
But I can not do the same with $resource, hereafter what I did:
The table:
<tr ng-repeat="progetto in progetti | filter:progSearch | orderBy:orderByField:reverseSort">
<td style="padding:10px;"><img src="images/user-2.png" href="#" width="25" ng-click="GetProgById(progetto.ID_Progetto)" data-toggle="modal" data-target="#progetto-modal" alt="Vista" /></td>
<td style="padding:10px;"><img src="images/edit-user.png" href="#" width="25" ng-click="GetProgById(progetto.ID_Progetto)" data-toggle="modal" data-target="#progetto-update-modal" alt="Modifica" /></td>
<td style="padding:10px;">{{progetto.NomeProgetto}}</td>
<td style="padding:10px;">{{progetto.Descrizione}}</td>
<td style="padding:10px;">{{progetto.NomeAreaRicerca}}</td>
<td style="padding:10px;">{{progetto.Responsabile}}</td>
<td style="padding:10px;"><img src="images/delete-user.png" href="#" width="25" ng-click="GetProgById(progetto.ID_Progetto)" data-toggle="modal" data-target="#modalEliminaProgetto" alt="Elimina" /></td>
</tr>
The module:
var app = angular.module('myApp', ['ngResource'])
.factory('progettiService', function ($resource) {
return $resource('http://localhost:12345/api/WebApiTest/ProgettiList');
// ProgettiList is specified below
});
The controller:
app.controller('progCtrl', function ($scope, progettiService) {
$scope.progetti = progettiService.query();
});
"ProgettiList" in api:
[HttpGet]
public IHttpActionResult ProgettiList()
{
var listProg = logic.ProgettiList();
return Ok(listProg);
}
in logic...
public List<ProgettoDAO> ProgettiList()
{
return progDAL.ProgettiListDAL();
}
and in DAL:
public List<ProgettoDAO> ProgettiListDAL()
{
List<ProgettoDAO> list = new List<ProgettoDAO>();
string SC = ConfigurationManager.ConnectionStrings["Connection"].ToString();
SqlConnection conn = new SqlConnection(SC);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "SP_Progetti_List";
cmd.Parameters.AddWithValue("#ID_Progetto", null);
try
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ProgettoDAO progetto = new ProgettoDAO();
if (reader["ID_Progetto"] != System.DBNull.Value)
{
progetto.ID_Progetto = Convert.ToInt16(reader["ID_Progetto"]);
}
if (reader["NomeProgetto"] != System.DBNull.Value)
{
progetto.NomeProgetto = Convert.ToString(reader["NomeProgetto"]);
}
if (reader["Responsabile"] != System.DBNull.Value)
{
progetto.Responsabile = Convert.ToString(reader["Responsabile"]);
}
if (reader["Descrizione"] != System.DBNull.Value)
{
progetto.Descrizione = Convert.ToString(reader["Descrizione"]);
}
if (reader["ID_AreaRicerca"] != System.DBNull.Value)
{
progetto.ID_AreaRicerca = Convert.ToInt16(reader["ID_AreaRicerca"]);
}
if (reader["NomeAreaRicerca"] != System.DBNull.Value)
{
progetto.NomeAreaRicerca = Convert.ToString(reader["NomeAreaRicerca"]);
}
list.Add(progetto);
}
conn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
conn.Close();
conn.Dispose();
}
return list;
}
The table should fill as soon as the page loads. However, the method returns a list Count = 0;

How to display/store and retrieve image as varbinary(MAX) using ASP.NET MVC view

I am new to ASP.NET MVC, so kindly excuse for mistakes.
I need a view page (index.cshtml) where I can display the image, change/delete the image by storing it in Varbinary(max) column in a SQL Server table.
There are these columns in the database table:
ID int primary key Identity not null,
ImageName nvarchar(50) ,
ImagePicInBytes varbinary(MAX) null
I am using a Image.cs with this code:
public class Image
{
public int ID {get; set;}
public string ImageName {get; set;}
public byte[] ImagePicInBytes {get; set;}
}
ImageContext class as below
public class ImageContext : DbContext
{
public DbSet<Image> Images { get; set; }
}
Connection string as below
<connectionStrings>
<add name="ImageContext"
connectionString="server=.; database=Sample; integrated security =SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
ImageController as below
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
}
Have created views as below
public class ImageController : Controller
{
private ImageContext db = new ImageContext();
// GET: /Image/
public ActionResult Index()
{
return View(db.Images.ToList());
}
// GET: /Image/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// GET: /Image/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Image image = db.Images.Find(id);
if (image == null)
{
return HttpNotFound();
}
return View(image);
}
// POST: /Image/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Image image = db.Images.Find(id);
db.Images.Remove(image);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
My create.cshtml (view) as below
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ImageName)
</th>
<th>
#Html.DisplayNameFor(model => model.ImagePicInBytes)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ImageName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ImagePicInBytes)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
I have the below 3 questions
How can I create a new record in datatable by uploading new image from file system to Varbinary column in database?
How can I have the view to have FILEUPLOAD control in the 'create View' and 'Edit view'
Can I use HttpPostedFileBase to achieve the above from Create.cshtml? If yes: how? Any suggestions or reference links available?
first of all create a viewmodel for Image class
public class ImageViewModel
{
public string ImageName {get; set;}
public HttpPostedFileBase ImagePic {get; set;}
}
then for uploading a photo in your create view
#model ExmpleProject.Models.ImageViewModel
#using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new {enctype="multipart/form-data"})){
#Html.AntiForgeryToken()
#Html.LabelFor(m => m.ImageName)
#Html.TextBoxFor(m => m.ImageName)
#Html.LabelFor(m => m.ImagePic )
#Html.TextBoxFor(m => m.ImagePic , new { type = "file" })
<br />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
then in post method of your controller for create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageViewModel model)
{
if (ModelState.IsValid)
{
var uploadedFile = (model.ImagePic != null && model.ImagePic.ContentLength > 0) ? new byte[model.ImagePic.InputStream.Length] : null;
if (uploadedFile != null)
{
model.ImagePic.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
}
Image image = new Image
{
ImageName = model.ImageName,
ImagePicInBytes = uploadedFile
}
db.Create(image);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
so for your edit method you can do similar implementation but instead of Create(image) use Update(image)

Http post in angularjs sends empty object

I'm learning AngularJS and I've been trying to send data from a controller using $http.post to a web api, but I keep getting empty data.
Any idea why? Tks in advance
This is my angular code
<!doctype html>
<html>
<head>
<title>Product Add</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body ng-app="ProductAdd">
<script>
var app = angular.module('ProductAdd', []);
app.controller('ProductAddController', ['$scope', '$http', function ($scope, $http) {
$scope.submit = function () {
if ($scope.Name) {
var product = {
"Name": $scope.Name,
"Category": $scope.Category,
"Price": $scope.Price
}
$http.post('http://localhost:1110/api/product', JSON.stringify(product)).
success(function () {
alert('Product Added Successfully');
}).
error(function () {
alert("erro");
});
}
};
}]);
</script>
<h2>Add New Product</h2>
<form ng-submit="submit()" ng-controller="ProductAddController">
<div>Name:<input type="text" ng-model="Name" required></div><br />
<div>Category:<input type="text" ng-model="Category" required> </div> <br />
<div>Price:<input type="text" ng-model="Price"> </div> <br />
<div> <input type="submit" id="productsubmit" value="Submit" /></div> <br />
</form>
</body>
</html>
This is my Web Api controller code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using Product_API.Models;
namespace Product_API.Controllers
{
[EnableCors("http://localhost:3442", "*","*")]
public class ProductController : ApiController
{
public static Lazy<List<Product>> Products = new Lazy<List<Product>>();//Static variable use only for demo, don’t use unless until require in project.
public static int PgaeLoadFlag = 1; // Page load count.
public static int ProductId = 4;
public ProductController()
{
if (PgaeLoadFlag == 1) //use this only for first time page load
{
//Three product added to display the data
Products.Value.Add(new Product { ID = 1, Name = "bus", Category = "Toy", Price = 200 });
Products.Value.Add(new Product { ID = 2, Name = "Car", Category = "Toy", Price = 300 });
Products.Value.Add(new Product { ID = 3, Name = "robot", Category = "Toy", Price = 3000 });
PgaeLoadFlag++;
}
}
// GET api/product
public List<Product> GetAllProducts() //get method
{
//Instedd of static variable you can use database resource to get the data and return to API
return Products.Value; //return all the product list data
}
// GET api/product/5
public IHttpActionResult GetProduct(int id)
{
Product product = Products.Value.FirstOrDefault(p => p.ID == id);
return product == null ? (IHttpActionResult) NotFound() : Ok(product);
}
**// POST api/product
[AcceptVerbs("OPTIONS")]
public void ProductAdd(Product product) //post method
{
product.ID = ProductId;
Products.Value.Add(product);
ProductId++;
}**
}
}
and this is my model
namespace Product_API.Models
{
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public int Price { get; set; }
}
}
Just don't stringify your object:
$http.post('http://localhost:1110/api/product', product)

Resources