I'm trying to dynamically load partial view with a different model instances inside of main view. Everything is working fine, until I have to reload partial view content. Then I have to reload 1 select list options, that is not in model. I have js method for that. Problem is, sometimes options are added, and disapear instantly. What am I doing wrong?
There are no any methods, that are changind this select control.
Main view:
<div id="tableContainer">
#{Html.RenderPartial("_TableView", Model.Tables[0]);}
</div>
<script type="text/javascript">
function loadTable () {
var selectedElement = $("#tableSelect").children("option:selected").val();
$("#tableContainer").load("/Home/UpdateTable/" + selectedElement);
getDishes();
};
window.onload = function () {
getDishes();
};
</script>
getDishes function:
function getDishes() {
$.ajax({
type: "GET",
url: "/GetDishes",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
success: function (result) {
if (result.success) {
fillDishList(result.message);
}
else
alert("Błąd podczas pobierania dostępnych dań! Treść błędu: " + result.message);
}
})
}
And fillDishList function:
function fillDishList(list) {
for (var a = 0; a < list.length; a++) {
var element = { val: a, text: list[a].Name };
$("#dishes").append($("<option>").attr('value', element.val).text(element.text));
}
updateDishPrice();
}
EDIT
Ok I got it working. There was timing issue. Function that should append elements to select list were launched before partial view were completely loaded. Here is solution:
<script type="text/javascript">
function loadTable () {
var selectedElement = $("#tableSelect").children("option:selected").val();
$("#tableContainer").html("");
$("#tableContainer").load("/Home/UpdateTable/" + selectedElement);
window.requestAnimationFrame(ready);
};
var ready = function () {
var dishes = $("#dishes");
if (dishes) {
getDishes();
if (dishes.children().length != 0)
return;
};
window.requestAnimationFrame(ready);
};
window.onload = function () {
getDishes();
};
</script>
Related
I posted this yesterday but i may not have explained my situation well.
I have 3 grids on a page that are built dynamically through JavaScript.
I then have 3 separate JavaScript methods to set a session when a row is clicked in a certain grid.
Once the session is set i would like it to navigate to the next page.
Here is what i have
OnClick event
$('#clinician-planned').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetPASession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-recent').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetRDSession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-theatre').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetTESession", "Clinician")';
AjaxCall(Location, ID);
});
AJAX Post To Controller
function AjaxCall(Location, ID) {
alert('1');
$.ajax({
type: 'POST',
url: Location,
dataType: 'text',
async: false,
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).done(function (response) {
alert('2');
location.href = "#Url.Action("Summary", "Patient")" + "/" + ID;
});
}
Here are the controller methods
public ActionResult SetPASession()
{
Session.Remove("Clinician");
Session["Clinician"] = "pa";
return Json(null);
}
public ActionResult SetRDSession()
{
Session.Remove("Clinician");
Session["Clinician"] = "rd";
return Json(null);
}
public ActionResult SetTESession()
{
Session.Remove("Clinician");
Session["Clinician"] = "te";
return Json(null);
}
The problem i have is when the row is clicked "alert('1'); shows instantly, however it seems like it takes a while and waits for all grids to be populated before the 2nd alert appears. I have tried putting async: false, but this doesnt seem to work.
Any ideas would be much appreciated.
I have a script that get's some data from the backend and populates the select2 dropdown. The problem is that the ajax call is called 2 times always and it should not be like this. I am not sure what I am doing wrong... any help would be apreciated.
this is my code:
var select2Element = $('select').select2({
theme: "classic",
escapeMarkup: function (markup) { return markup; },
});
select2Element.on('select2:opening', function(event) {
var clicked = $(this);
var route = "{{ path('get_attribute_list', {'articleId': 'ARTICLEID', 'attributeGroupId': 'ATTRIBUTEGROUPID'}) }}"
var url = route.replace("ARTICLEID", $(this).attr('data-articleId')).replace('ATTRIBUTEGROUPID', $(this).attr("data-attributeGroupId"));
$.ajax ({
url: url,
dataType: 'json',
async: false,
type: "GET",
}).then(function (data) {
//#TODO get out elements already inserted
for (var d = 0; d < data.length; d++)
{
var item = data[d];
// Create the DOM option that is pre-selected by default
var option = new Option(item.text, item.id, true, true);
// Append it to the select
clicked.append(option);
}
// Update the selected options that are displayed
clicked.trigger('change');
});
});
var inputResult = [];
select2Element.on('select2:select', function(e) {
var jsonValue = {
"articleId": $(this).attr("data-articleId"),
"attributeGroupId": $(this).attr("data-attributeGroupId"),
"attributeId": e.params.data.id
}
inputResult.push(jsonValue);
$('#addAttributes').val(JSON.stringify(inputResult));
});
select2Element.on('select2:close', function() {
$(this).html('');
});
Seems there is a bug in 'select2:open' and 'select2:opening'. There is a fix for this but not published.
Anyway who has this problem until it is fixed can see more details here:
https://github.com/select2/select2/issues/3503
and the fix for this here:
https://github.com/select2/select2/commit/c5a54ed70644598529a4071672cca4a22b148806
I'm very new to ajax/javascript so I will try my best to explain my problem. Here's what I have so far:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).val());
console.log($(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default.aspx",
type: "post",
dataType: "json",
data: { UpdateQuery: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
Every time a checkbox is checked, ajax passes the data onto the server. Here is an example of some checkbox values after a few have been checked in the data form obtained from the Developer's Console:
You can try the following code:
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
I basically have 2 drop-down lists and 2 labels.
The first drop-down list is the category selection and the second list loads dynamically the items based on the category.
All is good until now.
At the labels I am trying to display the ItemName and the ItemDescription.
ItemName displays fine but when it comes to ItemDescription for some reason it shows [object Object].
I noticed in console that ItemDescription information is posted correctly, can you please help me find the way to display it correctly?
Jquery:
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").text(this.ItemDescription));
});
}
});
});
</script>
Json:
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = from s in db.Items
where s.ItemType.ItemTypeName == itemTypeId && s.ItemActive == true
select new { Value = s.ItemName, ItemsID = s.ItemId ,ItemDescription = s.ItemDescription };
return Json(data);
}
$("#ItemsID option:selected").text(this.ItemDescription); changes the text and returns the element as an object. You can save the description of each item as data with jquery data() function. Then use it in change event..
try changing to this.
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
options.data('description','');
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value));
options.data('description',this.ItemDescription);
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").data('description'));
});
}
});
});
</script>
I did some play around and I found the solution :
<script type="text/javascript">
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function (results) {
var options = $('#ItemsID');
options.empty();
options.append($('<option />').val(null).text("- Select an Item -"));
options.data('description', '');
$.each(results, function () {
options.append($('<option />').val(this.ItemsID).text(this.Value).data('ItemDescription', this.ItemDescription));
});
$('#ItemsDivId').show();
$('#ItemsID').change(function (results) {
$('#SubmitID').show();
$('#ItemName').text($("#ItemsID option:selected").text());
$('#ItemDescription').text($("#ItemsID option:selected").data('ItemDescription'));
});
}
});
});
</script>
Also many thanks to Sampath Liyanage for leading me to the right direction :)
I'm having some problem with passing a javascript array to the controller. I have several checkboxes on my View, when a checkbox is checked, its ID will be saved to an array and then I need to use that array in the controller. Here are the code:
VIEW:
<script type="text/javascript">
var selectedSearchUsers = new Array();
$(document).ready(function () {
$("#userSearch").click(function () {
selectedSearchUsers.length = 0;
ShowLoading();
$.ajax({
type: "POST",
url: '/manage/searchusers',
dataType: "json",
data: $("#userSearchForm").serialize(),
success: function (result) { UserSearchSuccess(result); },
cache: false,
complete: function () { HideLoading(); }
});
});
$(".userSearchOption").live("change", function () {
var box = $(this);
var id = box.attr("dataId");
var checked = box.attr("checked");
if (checked) {
selectedSearchUsers.push(id);
}
else {
selectedSearchUsers.splice(selectedSearchUsers.indexOf(id), 1);
}
});
$("#Send").click(function () {
var postUserIDs = { values: selectedSearchUsers };
ShowLoading();
$.post("/Manage/ComposeMessage",
postUserIDs,
function (data) { }, "json");
});
});
</script>
When the "Send" button is clicked, I want to pass the selectedSearchUsers to the "ComposeMessage" action. Here is the Action code:
public JsonResult ComposeMessage(List<String> values)
{
//int count = selectedSearchUsers.Length;
string count = values.Count.ToString();
return Json(count);
}
However, the List values is always null. Any idea why?
Thank you very much.
You might try changing the controller's action method to this:
[HttpPost]
public JsonResult ComposeMessage(string values)
{
JavaScriptSerializer jass = new JavaScriptSerializer;
AnyClass myobj = jass.Deserialize<AnyClass>((string)values);
...
...
}
I believe that you have to take the JSON data in as a string and do the conversion
manually. Hope it helps. Cheers.