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;
Related
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;
};
}
});
I have 2 methods that take it out of a video to be able to list images from the database to my ssitea in a jsp, what happens is that my system lists the images of a single person and they are repeated, when it should be showing the photo of each
method to list
public ArrayList<CitaVO> listarCitas(String cliente_idCliente) {
CitaVO citVO = null;
conexion = this.obtenerConexion();
ArrayList<CitaVO> listaCitas = new ArrayList<>();
try {
sql = "SELECT * FROM vwcitasactivas WHERE cliente_idCliente=?";
puente = conexion.prepareStatement(sql);
puente.setString(1, cliente_idCliente);
mensajero = puente.executeQuery();
while (mensajero.next()) {
citVO = new CitaVO(mensajero.getString(1),
mensajero.getString(2), mensajero.getBinaryStream(3),
mensajero.getString(4), mensajero.getString(5),
mensajero.getString(6), mensajero.getString(7),
mensajero.getString(8), mensajero.getString(9),
mensajero.getString(10), mensajero.getString(11),
mensajero.getString(12),cliente_idCliente);
listaCitas.add(citVO);
}
} catch (Exception e) {
Logger.getLogger(ProAgendaDAO.class.getName()).log(Level.SEVERE, null, e);
}
return listaCitas;
}
method to list images
public void listarImg(String cliente_idCliente,HttpServletResponse response){
InputStream inputStream= null;
OutputStream outputStream=null;
BufferedInputStream bufferedInputStream=null;
BufferedOutputStream bufferedOutputStream=null;
response.setContentType("image/*");
try {
conexion = this.obtenerConexion();
sql = "SELECT * FROM vwcitasactivas WHERE cliente_idCliente=?";
outputStream=response.getOutputStream();
puente = conexion.prepareStatement(sql);
puente.setString(1, cliente_idCliente);
mensajero = puente.executeQuery();
if (mensajero.next()) {
inputStream=(mensajero.getBinaryStream(3));
}
bufferedInputStream=new BufferedInputStream(inputStream);
bufferedOutputStream=new BufferedOutputStream(outputStream);
int i=0;
while((i=bufferedInputStream.read())!=-1){
bufferedOutputStream.write(i);
}
} catch (SQLException e) {
Logger.getLogger(CitaDAO.class.getName()).log(Level.SEVERE, null, e);
} catch (IOException ex) {
Logger.getLogger(CitaDAO.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
Conexion conexBd = new Conexion();
conexBd.cerrarConexion();
} catch (SQLException e) {
Logger.getLogger(CitaDAO.class.getName()).log(Level.SEVERE, null, e);
}
}
}
my jsp code
<%
<%
CitaVO citVO = new CitaVO();
CitaDAO citDAO = new CitaDAO();
ArrayList<CitaVO> listaCitas = citDAO.listarCitas(idCliente);
for (int i = 0; i < listaCitas.size(); i++) {
citVO = listaCitas.get(i);
%>
<tr>
<td>
<div class="round-img">
<img src="ImagenControlador?idCliente=<%=idCliente%>" alt="" width="50px" height="50px" >
</div>
</td>
<td><%=citVO.getUsuNombre()%> <%=citVO.getUsuApellido()%></td>
<td><%=citVO.getUsuCiudad()%></td>
<td><%=citVO.getCitFecha()%></td>
<td><%=citVO.getProDia()%></td>
<td><%=citVO.getCitDireccion()%></td>
<td><%=citVO.getCitHoraInicio()%></td>
<td><%=citVO.getCitHoraFin()%></td>
<td <%=citVO.getCitEstado()%>><span class="badge badge-primary">Activa</span></td>
<td style="text-align: center">
<span><i class="ti-eye color-default" style="font-size: 18px"></i> </span>
<span><i class="ti-pencil-alt color-success" style="font-size: 18px"></i></span>
<span><i class="ti-trash color-danger" style="font-size: 18px"></i> </span>
</td>
</tr>
<%}%
these are my two methods to list the information and images and my jsp code where I list everything and the next result is the following
As you can see, I list the same image when the last person should have a totally different photo, I don't know why this happens, I answer any questions in the comments
I'm trying to read data from a WS and attach it to a scope variable in angularjs.
The controller API looks like this:
public class ContactsController : ApiController
{
// GET: api/Contacts
public List<Contact> Get()
{
List<Contact> cl = new List<Contact>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Contacts", con);
try
{
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Contact c = new Contact();
c.Name = rdr["Name"].ToString();
c.Phone = (int)rdr["Phone"];
c.Mail = rdr["Mail"].ToString();
c.City = rdr["City"].ToString();
c.Address = rdr["Address"].ToString();
c.Image = rdr["Image"].ToString();
cl.Add(c);
}
rdr.Close();
}
catch (Exception e)
{
}
finally
{
con.Close();
}
return cl;
}
The HTML controller looks like this:
controller: function ($scope, $http) {
var url = "http://example.com"
$http.get(url + "/api/Contacts").then(function (res) {
$scope.contacts = res.data;
}, function (err) { alert(err);});
but res.data seems to contain nothing.
Any help would be appreciated.
Thank you
You have just returning List<Contact> object, You can directly use the response instead of response.data.
Just try this code instead of yours
$scope.contacts = res;
Should check return cl; is returning any result
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;
}
}
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.