Angular ng-repeat only showing the first item - asp.net-mvc

I have the following table:
<div data-ng-app="myApp">
<div data-ng-controller="MyCtrl">
<form>
<table>
<tr>
<td><b>ID</b></td>
<td><b>Name</b></td>
<td><b>Surname</b></td>
<td><b>House</b></td>
<td><b>Address</b></td>
<td><b>Locality</b></td>
<td><b>Contact1</b></td>
<td><b>Contact2</b></td>
<td><b>Contact3</b></td>
<td><b>Reply</b></td>
</tr>
<tr><td></td></tr>
<tr ng-repeat="telesale in telesales">
<td>{{telesale.ID}}</td>
<td>{{telesale.Name}}</td>
<td>{{telesale.Surname}}</td>
<td>{{telesale.House}}</td>
<td>{{telesale.Address}}</td>
<td>{{telesale.Locality}}</td>
<td>{{telesale.Contact1}}</td>
<td>{{telesale.Contact2}}</td>
<td>{{telesale.Contact3}}</td>
<td>{{telesale.Reply}}</td>
</tr>
</table>
</form>
</div>
</div>
Angular:
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl',['$scope', '$http', function ($scope, $http) {
GetPersons();
function GetPersons() {
$http({
method: 'GET',
url: '/api/data'
}).
success(function (data) {
if(data != null || data != 'undefined') {
$scope.telesales = data;
}
})
.error(function (error) {
$window.alert("Unable to retrieve people" + error.message);
});
}
} ]);
</script>
The data being retrieved from the api is a list with a count of 40 rows (made a breakpoint to verify), however only the row from the list is being displayed. Why could this be happening?

That maight happend when your webapi controller return HttpResponseMessage message instead of pure data, in that case to get data you have to use result.data ie:
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl',['$scope', '$http', function ($scope, $http) {
GetPersons();
function GetPersons() {
$http({
method: 'GET',
url: '/api/data'
}).
success(function (result) {
if(result.data != null || result.data != 'undefined') {
$scope.telesales = result.data;
}
})
.error(function (error) {
$window.alert("Unable to retrieve people" + error.message);
});
}
} ]);
</script>

Related

Select2 initSelection element Val

I am using the select2 control on my web aplciation. In the initSelection I am passing the element.val() to a controller but it is null. How would I set element.val() that i want pass to the Url.Action. Is element.val() the correct object that I should be using when I am using a div?
I see the value in Chrome
debugger
view
<div id="guideline-container" style="#(Model.Type == "Guideline" ? "display:block" : "display:none")">
<form id="guideline-form" class="form-horizontal">
<div class="form-group">
<label for="guidelineName" class="col-sm-2 control-label">Guideline</label>
<div class="col-sm-10">
<div id="guidelineName">
#{ Html.RenderAction("Index", "GuidelinesPicklist", new { value = Model.GuidelineId, leaveOutAlgorithmItems = true, separateActiveItems = true }); }
</div>
<div class="guideline-not-selected field-validation-error" style="display: none;">
Guideline is required.
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary modal-submit-btn">Add</button>
<button type="button" class="btn btn-default modal-close-btn" data-dismiss="modal">Close</button>
</div>
</form>
</div>
function
$(this).select2({
placeholder: "#Model.Settings.Placeholder",
//allowClear: true,
ajax: {
url: "#Url.Action("GetPicklistItems")",
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: function (params) {
return JSON.stringify({
query: params.term,
args: #Html.Raw(JsonConvert.SerializeObject(#Model.Settings != null ? #Model.Settings.AdditionalArguments : null))
});
},
processResults: function (data, page) {
console.log("processResults");
console.log(data);
var resultData = [];
if (isError(data)) {
showErrorMessage(getErrorMessage(data));
} else {
hideErrorMessage();
mapResultData(data.Result, resultData, 0);
}
return {
results: resultData
};
}
},
templateResult: format,
templateSelection: function(data) {
return data.text;
},
initSelection: function (element, callback) {
//console.log("initSelection");
//var id = $(element).val();
//console.log(id);
var guidelineId = "#Model.Value";
console.log("guidelineId");
console.log(guidelineId);
//console.log("params");
//console.log(params);
//console.log("element object Text");
//console.log(element.text);
debugger;
getAjax("#Url.Action("GetPicklistItem")" + "?value=" + guidelineId, function (result)
{
console.log("Ajax GetPicklistItem");
console.log(result);
debugger;
if (result.Result) {
var data = {};
$.extend(data, result.Result);
data.id = result.Result.Value;
data.text = result.Result.Text;
callback(data);
self.trigger("picklistChanged", data);
} else {
console.log(result);
debugger;
callback ({ id: null, text: "#Model.Settings.Placeholder" })
}
});
},
escapeMarkup: function(m) {
return m;
}
}).on('change', function () {
var data = self.select2('data');
self.trigger("picklistChanged", data);
});
You can get Select2 selected value or text by using the following approaches:
var selectedValue = $('#Employee').val();
var selectedText = $('#Employee :selected').text();
Alternatively you can simply listen to the select2:select event to get the selected item:
$("#Employee").on('select2:select', onSelect)
function onSelect(evt) {
console.log($(this).val());
}

I have a Rails app using React posting to my db using an ajax call. How do I handle the redirect?

So I have my Rails app trying to submit a cohort to the database. I can get it to post to the database but I do not know how to handle the redirect.
var NewCohort = React.createClass ({
getInitialState: function() {
return {name:'',description:''}
},
handleNameChange: function(e) {
this.setState({name:e.target.value})
},
handleDescriptionChange: function(e) {
this.setState({description:e.target.value})
},
handleSubmit: function(e) {
var that = this
$.ajax({
url: '/cohorts',
method: 'POST',
data: {
name: that.state.name,
description: that.state.description
},
success: function(data, success, xhr) {
console.log(data)
}
})
},
render: function() {
return (
<div className="container">
<h3>Create a new cohort</h3>
<form onSubmit={this.handleSubmit}>
<input type="text" value={this.state.name} onChange={this.handleNameChange}/>
<input type="text" value={this.state.description} onChange={this.handleDescriptionChange}/>
<input type="submit"/>
</form>
</div>
)
}
})
Is my ajax call which I send to my controller which has
def create
#cohort = Cohort.create(name: params[:name], description: params[:description])
render component: 'ShowCohort', props: { cohort: #cohort }
end
Which in my ajax success function, the data is the new React html code. How to I actually redirect the the page?
This is my React component to render
var ShowCohort = React.createClass ({
render: function() {
return (
<div className="container">
<h3>Hello {this.props.cohort.name}</h3>
<p>{this.props.cohort.description}</p>
</div>
)
}
})
Don't use ajax. Just use a regular form.
this should be like this
success: function(data, success, xhr) {
window.location.href = "redirect_url";
}
you can pass it as json as well like this in your controller
render json: {"redirect":true,"redirect_url": apps_path}, status:200
success: function(data, success, xhr) {
window.location.href = data.redirect_url;
}

load data from db knockoutjs + mv3

attached the file EXAMPLE: http://jsfiddle.net/brux88/9fzG4/1/
hi,
I'm starting to use knockoutjs in an asp.net mvc project.
i have a view :
<button data-bind='click: load'>Load</button>
<table>
<thead>
<tr>
<th>Cliente</th>
<th>Colli</th>
<th>Tara</th>
<th>Peso Tara</th>
<th> </th>
</tr>
</thead>
<tbody data-bind='foreach: righe'>
<tr>
<td>
<select data-bind="
value: selectedCli,
options: clienteList,
optionsText: function(item) { return item.Rscli + '-' + item.Codcli },
optionsCaption: '--Seleziona un Cliente--'"
style=" width: 150px">
</select>
</td>
<td >
<input data-bind='value: Ncolli' />
</td>
<td>
<select data-bind="value: selectedTara,
options: taraList,
optionsText: function(item) { return item.Destara +
'-' + item.Codtara},
optionsCaption: '--Seleziona un Cliente--'"
style=" width: 150px">
</select>
</td>
<td >
<input data-bind="value: Ptara" />
</td>
<td>
<a href='#' data-bind='click: $parent.rimuoviRiga'>Elimina</a>
</td>
</tr>
</tbody>
</table>
<button data-bind='click: aggiungiRiga'>Aggiungi</button>
<button data-bind='click: salva'>Salva</button>
<button data-bind='click: annulla'>Annulla</button>​
my result from data db:
[{"Codcli":4,"Rscli":"antonio","Codtart":"1002","Despar":"ciliegino","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":82,"Pnetto":18,"Prezzo":1},{"Codcli":1,"Rscli":"bruno","Codtart":"1001","Despar":"pomodoro","Ncolli":10,"Pcolli":100,"Codtara":"03","Destara":"","Ptara":10,"Pnetto":90,"Prezzo":1}]
my viewmodel knockoutjs:
<script type="text/javascript">
var listCli= [{Codcli: 1,Rscli: "Bruno"},{Codcli: 2,Rscli: "Pippo"},{Codcli: 3,Rscli: "Giacomo"}];
var listTa= [{Codtara: 01,Destara: "Plastica",Pertara:4},{Codtara: 02,Destara: "Legno",Pertara:6},{Codtara: 03,Destara: "Ploto",Pertara:8}];
var mydataserver = [{"Codcli":3,"Rscli":"Giacomo","Ncolli":10,"Codtara":"03","Destara":"Legno","Ptara":82},{"Codcli":1,"Rscli":"Bruno","Ncolli":10,"Codtara":"02","Destara":"Plastica","Ptara":10}];
var RigaOrdine = function () {
var self = this;
self.selectedCli = ko.observable();
self.clienteList = ko.observableArray(listCli);
self.Ncolli = ko.observable();
self.selectedTara = ko.observable();
self.taraList = ko.observableArray(listTa);
self.Ptara = ko.observable();
self.Ncolli.subscribe(function () {
self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : 0);
});
self.selectedTara.subscribe(function () {
self.Ptara(self.Ncolli() ? self.selectedTara().Pertara * self.Ncolli() : self.selectedTara().Pertara);
});
};
var Ordine = function () {
var self = this;
self.righe = ko.observableArray([new RigaOrdine()]); // Put one line in by default
// Operations
self.aggiungiRiga = function () {
self.righe.push(new RigaOrdine());
};
self.rimuoviRiga = function (riga) {
self.righe.remove(riga);
};
self.salva = function() {
var righe = $.map(self.righe(), function (riga) {
return riga.selectedCli() ? {
Codcli: riga.selectedCli().Codcli,
Rscli: riga.selectedCli().Rscli,
Ncolli: riga.Ncolli(),
Codtara: riga.selectedTara().Codtara,
Ptara: riga.Ptara(),
} : undefined;
});
alert( ko.toJSON(righe));
//save to server
/* $.ajax({
url: "/echo/json/",
type: "POST",
data: ko.toJSON(righe),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
}
});*/
self.righe([new RigaOrdine()]);
};
//load from server
self.load = function() {
$.ajax({ url: '/echo/json/',
accepts: "application/json",
cache: false,
statusCode: {
200: function (data) {
alert(ko.toJSON(mydataserver));
//i do not know apply to viewmodel
},
401: function (jqXHR, textStatus, errorThrown) {
alert('401: Unauthenticated');
// self.location = "../../Account/Login.html?returnURL=/Index.html";
}
}
});
};
self.annulla = function() {
self.righe([new RigaOrdine()]);
};
};
var viewmodel = new Ordine();
ko.applyBindings(viewmodel);
​
</script>
if I want to load data from a db, how do I? Whereas there are dropdownlist
Your question is a bit weak so I will give you a more general answer.
To answer your question regarding how to load data from a db, it looks like that you have started on the right track. Usually you use an AJAX request to do the async request of data. To do this, knockoutJS provides the following function:
$.getJSON("/some/url", function(data) {
// Now use this data to update your view models,
// and Knockout will update your UI automatically
})
Source: http://knockoutjs.com/documentation/json-data.html
In the callback provided you will have access to the data returned from the server. It depends on the logic of your application what you want to do here - for some applications it might make sence to update the state of the viewmodel to make corresponding updates in the view.
If your question is more specific, please elaborate. Otherwise, I hope I got you on the right track.
As i can see.. you may want some good pratice to load.
I'll share with you mine.
Well.. return a Json as an JsonResult.
// POST: /Client/LoadClient
[HttpPost]
public JsonResult LoadClient(int? id)
{
if (id == null) return null;
var client = _business.FindById((int) id);
return Json(
new
{
id = cliente.id,
name = cliente.name,
list = cliente.listOfSomething.Select(s => new {idItemFromList = s.idWhatever, nameItemFromList = s.nameWhatever})
});
}
JS
viewmodel.Client.prototype.LoadClient= function (id) {
var self = this;
if (id == 0) {
return null;
}
$.ajax({
url: actionURL("LoadClient", "Client"),
data: { id: parseInt(id) },
dataType: "json",
success: function (result) {
if (result != null)
self.Load(result);
}
});
Load method.
viewmodel.Client.prototype.Load = function (result) {
var self = this;
self.idClient(result.id);
self.nameCliente(result.name);
self.ListOfSomething(result.list);
};
and..
ko.applyBinding(yourModel);
as u can see I'm using prototype it's a good practice too.

dataTable refresh on ajax success

I have the data table from the jquery plugin dataTables (http://datatables.net/) that I want to refresh upon ajax success. I tried the following code but its not working. Any help will be appreciated
$(document).ready(function() {
oTable = $('#mytable').dataTable();
var fa = 0;
$('#submit tbody td ').click(function() {
var gCard = $('#mytable tbody').delegate("tr", "click", rowClick);
});
function rowClick() {
fa = this;
var id = $("td:eq(1)", this).text();
cardNumber = $.trim(id);
$.ajax({
url : 'myurltopostto',
type : 'POST',
data : {
id : id
},
success : function(data) {
oTable.fnDraw(); //wanted to update here
},
error : function() {
console.log('error');
}
});
}
});
You can use : fnDeleteRow which will take care of refreshing the table html and data internally, look up API details here:
http://datatables.net/ref
oTable.fnDeleteRow( fa );
hello my dears programers... sorry... my inglish is very bad but I help you... my following is this:
<script type="text/javascript">
function Ajax()
{
var
$http,
$self = arguments.callee;
if (window.XMLHttpRequest) {
$http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
$http = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) {
$http = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ($http) {
$http.onreadystatechange = function()
{
if (/4|^complete$/.test($http.readyState)) {
document.getElementById('ReloadThis').innerHTML = $http.responseText;
setTimeout(function(){$self();}, 10000);
$( this ).hide( "slow" );
}
};
$http.open('GET', 'cls_Noticias/last_noticias.php', true);
$http.send(null);
}
}
</script>
</head>
<body>
<script type="text/javascript">
setTimeout(function() {Ajax();}, 10000);
</script>
<div id="ReloadThis">Espere a que la pagina se actualice!</div>
</body>
good life!

Why is this jquery callback for complete not executed

The OnCompleteStuff is never called, what do I wrong?
<script type="text/javascript">
function OnBeginStuff() {
$("#StuffPanel").fadeTo("slow", 0.50);
}
function OnCompleteStuff(request, status) { // Never called
$("#StuffPanel").fadeTo("slow", 1.00);
}
$(document).ready(function () {
$('.mainLink', $('#NavigationPanel')).click(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr('href'),
beforeSend: OnBeginStuff,
complete: OnCompleteStuff,
success: function (html) {
$('#StuffPanel').html(html);
}
});
});
});
</script>
</head>
<body>
<div id="NavigationPanel">
#Html.ActionLink("1", "Index", "One", null, new { #class = "mainLink" })
#Html.ActionLink("2", "Index", "Two", null, new { #class = "mainLink" })
#Html.ActionLink("3", "Index", "Three", null, new { #class = "mainLink" })
</div>
<div id="StuffPanel">
#RenderBody()
</div>
</body>
</html>

Resources