Why is this jquery callback for complete not executed - asp.net-mvc

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>

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());
}

Angular ng-repeat only showing the first item

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>

Dymanic listview construction visible in jQuery Mobile 1.4.2 transition

I have a Single Page transition from #homepage to #addresses where the page #addresses include a dynamic listview build based in an $.ajax WebApi call.
The problem is that it's visible the construction of the listview when we arrive at the second page, and I want to avoid that, I want the list all build when we land in the #addresses page.
I also have a delay click in the listview in iPhone.
My code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>izigo.mobile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).bind("mobileinit", function ()
{
$.mobile.toolbar.prototype.options.addBackBtn = true;
$.mobile.toolbar.prototype.options.backBtnText = "voltar";
$.mobile.page.prototype.options.domCache = true;
});
</script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
/* Pass data with changePage */
$(document).on("pageinit", "#homepage", function ()
{
$(".category").on("click", function ()
{
$.mobile.pageContainer.pagecontainer("change", "#addresses",
{
categoryId: this.id,
transition: "slide"
});
});
});
/* retrieve data and run function to add elements */
$(document).on("pagebeforechange", function (e, data)
{
if (data.toPage[0].id == "addresses")
{
var categoryId = data.options.categoryId;
clearListCategory("#addresses");
buildListCategory("#addresses", categoryId);
}
});
function clearListCategory(page)
{
var $page = $(page);
$("ul", $page).remove();
}
function buildListCategory(page, categoryId)
{
$.ajax({
type: "POST",
url: "http://10.0.0.200/api/Mobile/GetAddresses",
crossDomain: false,
beforeSend: function () { $.mobile.loading('show') },
complete: function () { $.mobile.loading('hide') },
data: { CategoryId: categoryId },
dataType: 'json',
success: function (addresses)
{
showAddresses(page, addresses);
},
error: function () {
console.log("loadList error!");
}
});
}
function showAddresses(page, addresses)
{
var $page = $(page);
var list = $("<ul/>", {
"data-role": "listview"
});
var items = '';
$.each(addresses, function (i, address)
{
items = $("<li>" + address.Name + "</li>");
list.append(items);
});
$(".ui-content", $page).append(list);
$("ul", $page).listview();
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!-- home-page -->
<div data-role="page" id="homepage">
<div data-role="header" data-position="fixed"><h1>mobile</h1></div>
<div class="ui-content" role="main">
<ul data-role="listview" id="categories">
<li>Oficina</li>
<li>Seguro</li>
<li>Reboque</li>
</ul>
</div>
</div>
<!-- page addresses list -->
<div data-role="page" id="addresses">
<div data-role="header" data-position="fixed"><h1>mobile</h1></div>
<div class="ui-content" role="main"></div>
</div>
</body>
</html>
The code you're using, you populate listview on pagebeforechange event, which is triggered before any other page event. You should populate listview before you navigate to target page, using .success or .complete callback.
$.ajax({
type: "POST",
url: "URL",
crossDomain: false,
beforeSend: function () {
$.mobile.loading('show')
},
complete: function () {
$.mobile.loading('hide')
},
data: {
CategoryId: categoryId
},
dataType: 'json',
success: function (addresses) {
showAddresses(page, addresses);
$.mobile.pageContainer.pagecontainer("change", "#addresses");
},
error: function () {
console.log("loadList error!");
}
});
Demo - Code

bind the click event to all links in a div with a certain class name

The first parts of the jquery call inside the document.ready is pseudo code. How can I do the $('.mainLink').each().click() correctly so that all links with class name mainLinks inside the NavigationPanel are bound to the click event. Is it bad to not use an id for a link?
$(document).ready(function () {
$('.mainLink').each().click(function (e) {
e.preventDefault();
$.ajax({
url: this.href,
beforeSend: OnBegin,
complete: OnComplete,
success: function (html) {
$('#ContentPanel').html(html);
}
});
});
});
<div id="NavigationPanel">
#Html.ActionLink("1", "Index", "First", null, new { #class = "mainLink" })
#Html.ActionLink("2", "Index", "Two", null, new { #class = "mainLink" })
#Html.ActionLink("3", "Index", "Three", null, new { #class = "mainLink" })
</div>
Just do $('.mainLink').click(function (e) { which should bind all links with class .mainLink
If you want all links inside div ID NavigationPanel then try below,
$('.mainLink', $('#NavigationPanel')).click(function (e) {
If you just want to bind to all .mainLink within #NavigationPanel, the following works:
$("#NavigationPanel").on("click", ".mainLink", function(e){
e.preventDefault();
$.ajax({
url: this.href,
beforeSend: OnBegin,
complete: OnComplete,
success: function (html) {
$('#ContentPanel').html(html);
}
});
});

Dependency between DropDownList

I have 2 select field in ascx file:
<%=Html.DropDownList("CityID", new SelectList(Model.Cities, "Code", "Name"), new Dictionary<string, object>
{
{"class", "styled"}
})
%>
<%=Html.DropDownList("EstablishmentID", new SelectList(Model.Establishments, "OID", "Name"),
"All Establishment", new Dictionary<string, object>
{
{"class", "styled"}
})
%>
I want that a values of EstablishmentId change when user select new value in CityID.
How can I do this?
Thanks.
PS. ViewEngine is WepPages.
cascading Country and state DDL
#Html.DropDownListFor(model => model.CountryId, Model.CountryList, "--Select Country--", new { #class = "CountryList", style = "width:150px" })
#Html.DropDownListFor(model => model.StateId, Model.StateList, "--Select State--", new { #class = "StateList", style = "width:150px" })
<script type="text/javascript">
$(document).ready(function () {
$.post("/Client/GetModels", { id: $(".CountryList").val() }, function (data) {
populateDropdown($(".StateList"), data);
});
$(".CountryList").change(function () {
$.post("/Client/GetModels", { id: $(this).val() }, function (data) {
populateDropdown($(".StateList"), data);
});
});
});
function populateDropdown(select, data) {
$(".StateList").empty();
$.each(data, function (id, option) {
$(".StateList").append("<option value='" + option.StateId + "'>" + option.State + "</option>");
});
}
</script>
Try this
In view
<div class="popup_textbox_div" style="padding: 0pt;">
<%=Html.DropDownList("CityId", new SelectList(Model.Cities, "Code", "Name", 0), "---Select City---", new { #class = "popup_textbox popup_dropdown valid" })%>
</div>
<div class="popup_textbox_div" style="padding: 0pt;">
<select class="popup_textbox popup_dropdown valid" id="OID" name="Name">
<option>---All Establishment---</option>
</select>
</div>
Add the script
<script type="text/javascript">
$(function () {
$("#CityId").change(function () {
var cityId = $("#CityId").val();
if (!isNaN(cityId) && ( cityId > 0) && ( cityId != null)) {
GetEstablishmentsByAjax(cityId);
}
else {
$("#OID").html("<option value=''>---All Establishment---</option>");
}
});
});
GetEstablishmentsByAjax(cid) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/trail/selectestablishment/" + cid.toString(),
data: "",
dataType: "json",
success: function (data) {
if (data.length > 0) {
var options = "<option value=''> --All Establishment---</option>";
for (s in data) {
var type = data[s];
options += "<option value='" + type.Value + "'>" + type.Text + "</option>";
}
$("#OID").html(options);
}
}
});
}
</script>
In TrailController
public ActionResult selectestablishment(int? id)
{
SelectList establishments = null;
var estb = //put ur code and get list of establishments under selected city
establishments = new SelectList(estb, "OID", "Name");
return Json(establishments, JsonRequestBehavior.AllowGet);
}

Resources