Dependent multiselect dropdown using chosen and select2 plugins - javascript

This is the code I have written in View :
<div class="col-lg-12" style="margin-bottom: 20px;">
<div class="form-group">
<label class="col-sm-3 control-label" style=" margin-top: 14px; ">Domains <font size="3" color="red">*</font></label>
<br />
<div class="col-sm-4" style="width:50%;">
#Html.ListBoxFor(m => m.SelectedDomains, Model.AllDomains,
new { #class = "chosen", multiple = "multiple", id = "drpDomains", style = "width: 350px;",onchange="FillDomain();" })
</div>
</div>
</div>
<div class="col-lg-12" style="margin-bottom: 20px;">
<div class="form-group">
<label class="col-sm-3 control-label" style=" margin-top: 14px; ">Domains new categories <font size="3" color="red">*</font></label>
<br />
<div class="col-sm-4" style="width:50%;">
#Html.ListBoxFor(m => m.SelectedDomainCategories, Enumerable.Empty<SelectListItem>(),
new { #class = "select2", multiple = "multiple", id = "multidomaincategory", style = "width: 350px;" })
</div>
</div>
</div>
<link href="~/Scripts/MultiSelect/chosen.css" rel="stylesheet" />
For Domains, I have used Chosen plugin, and for categories, i have used select2 plugin
<script type="text/javascript">
$(".chosen-deselect").chosen({ allow_single_deselect: true });
$(".chosen").chosen().change();
$(".chosen").trigger('liszt:updated');
</script>
<script>
function FillDomain() {
$("#drpDomains option[value='']").removeAttr("selected");
var selectArr = [];
$('#drpDomains').each(function () {
selectArr.push($(this).val());
});
var a = JSON.stringify(selectArr);
var reference = this;
$.ajax({
url: #Url.Content("~/MyTemplate2/FillIndustry1"), //FillIndustry1 is a method in Controller
type: "POST",
dataType: "JSON",
data: { Domain: a },
success: function (DomainCategories) {
$("#multidomaincategory").html("");
$("#multidomaincategory").removeAttr("selected");
var s = JSON.stringify(DomainCategories);
var t = JSON.parse(s);
for (var key in t) {
$("#multidomaincategory").append("<option value=" + t[key]["Value"] + ">" + t[key]["Text"] + "</option>");
}
},
error: function (data) {
alert("failure error" + data);
var t = window.JSON.parse(data.d);
alert("failueee" + t);
}
});
//I'm trying to remove all the selected items from dependent dropdown (#multidomaincategory) when all items from Domains(#drpDomains) are cleared
if ($("#drpDomains").val() == null || $("#drpDomains").val() == "") {
$("#multidomaincategory").removeAttr("selected");
$("#multidomaincategory").css('display', 'none');
}
}
</script>
Controller :
[HttpPost]
public ActionResult FillIndustry1(string Domain)
{
JArray jsonMembersArr = (JArray)JsonConvert.DeserializeObject(Domain);//convert SymptomString from json string to array
ProfessionalTrans objprofessionaltrans = new ProfessionalTrans();
string listdomains = "";
foreach (var a in jsonMembersArr)
{
listdomains = string.Join(",", a);
}
var DomainCategories = objprofessionaltrans.GetDepCategories(listdomains);
return Json(DomainCategories.ToList());
}
Data Access Layer(Transaction):
public IEnumerable<SelectListItem> GetDepCategories(string domains)
{
//GetDepCategories method - To get categories based on Domains
PTS_CommonEntities objentity = new PTS_CommonEntities();
List<SelectListItem> allskills = new List<SelectListItem>();
List<GetCatListbasedDomain> catnames = objentity.usp_GetCatListBasedOnDomains(domains).ToList();
foreach (var it in catnames)
{
allskills.Add(new SelectListItem { Value = it.CategoryID.ToString(), Text = it.CategoryName });
}
return allskills.AsEnumerable();
}
When I am clearing(closing) the selected items in Domains, the respective Categories are cleared from list, but not in the text box
Image Before Clearing
Image After Clearing the Domains
As you can see, the list is being cleared, but the selected items are still being shown in the UI.
Can someone please find out why the items are being displayed even after clearing them???

Because you are trying to clear the wrong element. #multidomaincategory is the select2 list that holds all of the values, there is a dynamic span class that gets rendered to the page right after this element, look at the html that select2 produces in your browser. Try:
$('#multidomaincategory').next().find('li').html('');
They are cleared from the list because $("#multidomaincategory").html(""); clears the html of the list of categories, not the rendered text elements in the text box.
Although a better way: $('#multidomaincategory').select2('data', null)

Related

Can't obtain values from controls through javascript in razor page

I have a razor page where evrything is displaying fine, but I need to be able to read the values inside a few controllers to pass them as parameters in an call to prefilter some data:
#page
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#model MyApp.Pages.IndexModel
#{
ViewData["Title"] = "MyApp";
}
<div class="col-12 border p-3 mt-3">
<h3>Filters</h3>
<div class="col-12">
<select id="portMultiselect" name="lsPorts" asp-items="#Model.Ports" multiple></select>
<input id="searchString" type="text" name="searchString">
</div>
</div>
#* A "REFRESHABLE" TABLE GOES HERE...*#
#section scripts{
#* REFRESH SCRIPT *#
<script type="text/javascript">
$(function () {
setInterval(loadTable, 60000);
loadTable();
});
function loadTable() {
var select1 = document.getElementById("portMultiselect");
var selectedPorts = [];
for (var i = 0; i < select1.options.length; i++) {
if (select1.options[i].selected) selectedPorts.push(select1.options[i].value);
}
var searchString = document.getElementById('searchString').value;
if (searchString != "" || selectedPorts.length != 0) {
debugger;
}
fetch('/Index?handler=IndexPartial', {
data: {
searchString: searchString,
selectedPorts: selectedPorts
}
})
.then((response) => {
return response.text();
})
.then((result) => {
document.getElementById('refreshable').innerHTML = result;
});
}
</script>
}
As you can see, I'm trying to capture the selected values in my multiselect and in a text input to pass as parameters in the refresh script.
I'm correctly arriving to the expected endpoint, but Im never getting any values (It's always empty and zero) I even added a debugger in the Javascript code that I'm never hitting.
Why can't I read those values?
EDIT:
I have seen other ways of dealing with these, such as databindings, but as mentioned here, the only way to avoid page reload is javascript and AJAX, so I still need to get these values from the javascript.
At the end, I found a solution to my predicament as follows:
I changed the way I render the selectPicker, following the examples shown in this page:
#page
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#model MyApp.Pages.IndexModel
#{
ViewData["Title"] = "MyApp";
}
<div class="col-12 border p-3 mt-3">
<h3>Filtros</h3>
<div class="row">
<div class="col-6">
<p>Puertos</p>
#Html.DropDownListFor(x =>
x.selectPort,
(IEnumerable<SelectListItem>)ViewData["MyPorts"],
new
{
#id = "portMultiselect",
#class = "form-control selectpicker",
#Value = #Model.Ports,
data_live_search = "true",
multiple = "multiple"
})
</div>
<div class="col-6">
<p>Nombre de variable</p>
<input id="searchString" type="text" name="searchString">
</div>
</div>
</div>
This comes with certain changes to the model you're working with, you can follow instructions to bind data as T.Trassoudaine commmented, here
for this to work you need to add the specified references in your _Layout (for the bootstrap-select), you can check all the things you need to add here
And finally, you will need to work with AJAX in javascript to pass the parameters back:
<script type="text/javascript">
$(function () {
setInterval(loadTable, 1000);
loadTable();
});
function loadTable() {
var select1 = document.getElementById("portMultiselect");
var selectedPorts = [];
for (var i = 0; i < select1.options.length; i++) {
if (select1.options[i].selected) selectedPorts.push(select1.options[i].value);
}
var searchString = document.getElementById('searchString').value.toUpperCase();
var searchPorts = "";
if (selectedPorts.length != 0) {
searchPorts = selectedPorts.join(",");
}
$.ajax({
url: '/?handler=IndexPartial',
data: {
searchString: searchString,
searchPorts: searchPorts
},
success: function (data) {
document.getElementById('refreshable').innerHTML = data;
}
})
}
</script>

ASP.Net MVC passing data from script to new view

Hi everyone and thanks for reading this message at first.
I am currently struggling with an ASP.Net MVC Framework project for passing data between views.
I have a controller Model with Index View and a javascript that helps me getting ids of objects clicked on a 3d model rendered in a canvas. Here is the view :
<div class="col-md-10">
<canvas id="viewer"></canvas>
</div>
<div class="col-md-2">
<btn id="AddEventObjects" class="btn btn-eiffage-red">Create a task</btn>
<table id="selectedElements" class="table table-striped">
<thead><tr><th>Selected parts</th></tr></thead>
</table>
</div>
<script type="text/javascript">
var viewer = new xViewer('viewer');
var selectedIds = [];
viewer.on('loaded',
() => {
viewer.start();
});
viewer.on('pick', function (args) {
if (args == null || args.id == null) {
return;
}
var id = args.id;
//If the id was previously clicked then remove it from the list and remove the highlight
if (selectedIds.includes(id)) {
var index = selectedIds.indexOf(id);
selectedIds.splice(index, 1);
} else {
selectedIds.push(id);
}
//Add elements to the table
var table = document.getElementById('selectedElements');
var oldtbody = document.getElementById('selectedElementsBody');
if (oldtbody) {
oldtbody.remove();
}
var tbody = document.createElement('tbody');
tbody.id = "selectedElementsBody";
for (var i = 0; i < selectedIds.length; i++) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = selectedProperties[i];
row.appendChild(cell);
tbody.appendChild(row);
table.appendChild(tbody);
}
});
viewer.load('../Content/3d/Maintenance.wexbim');
</script>
With the script under I would like to open another window passing the selectedIds array :
<script type="text/javascript">
$('#AddEventObjects').click(function () {
$.ajax({
url: "#(Url.Action("AddEventObjects", "Planning"))",
type: "GET",
dataType : "json",
data: { selectedObjects: selectedIds},
cache: false,
async: true,
traditional: true,
success: function (data) {
window.location = "/Planning/AddEventObjects";
},
error: function () {
alert("error");
}
});
});
</script>
Knowing that my controller Planning has an action called AddEventObjects:
public ActionResult AddEventObjects(string[] selectedObjects) {
ViewBag.Title = "Ajout intervention";
var addEventObjectsViewModel = new AddEventObjectsViewModel {
Title = "",
StartTime = "",
EndTime = "",
AllUsers = _context.Users.ToList(),
SelectedUsers = new List<ApplicationUser>(),
PostedUsers = new PostedUsers(),
ObjectsIds = selectedObjects.ToList(),
};
addEventObjectsViewModel.PostedUsers.SelectedIds = addEventObjectsViewModel.SelectedUsers.Select(x => x.Id).ToArray();
return View(addEventObjectsViewModel);
}
I would like it to open the following view that displays the selectedIds :
#model Maintenance.Web.Models.AddEventObjectsViewModel
using (Html.BeginForm("AddEvent", "Planning", FormMethod.Post, new { #class = "form-horizontal", role = "form" })) {
#Html.AntiForgeryToken()
<h4>Créer une nouvelle intervention</h4>
<div class="form-horizontal col-md-12">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-row col-md-12">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.ObjectsIds, htmlAttributes: new { #class = "control-label" })
<table class="table table-striped" style="width:100%; margin-top:20px">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
#if (Model != null) {
foreach (var objectId in Model.ObjectsIds) {
<tr>
<td>#objectId</td>
</tr>
}
}
</table>
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<div class="col-md-10">
<input type="submit" class="btn btn-eiffage-red" value="Ajouter" />
</div>
</div>
</div>
}
With a more basic question : how can I pass an array from a javascript in a view to another view?
Thanks a lot for your help.
If you are passing an array of data, there are a few ways. The easiest of ways is to do the following. Join the array IDS into a comma separated string:
var idList = data.PostedUsers.SelectedIds.join(); //comma sep list
window.location = "/Planning/AddEventObjects?ids=" + idList;
This would work with what you have very simply; it will build a URL like:
/Planning/AddEventObjects?ids=1,2,3,4
In the backend, you have a "string ids" parameter, and split it by comma, and use the IDs however you need to.
Thanks Brian Mains!
I went with passing data in the url as you suggested.
I just used Json serialized data instead of coma separated values :
<a id="CreateEvent" class="btn" href="">Créer une intervention</a>
...
var createLink = "/Planning/AddEventObjects?ids=" + JSON.stringify(model.ids);
$('#CreateEvent').attr("href", createLink);
And then in my controller :
public ActionResult AddEventObjects(string ids) {
if (ids == null) {
return HttpNotFound();
}
string[] objectIds = JsonConvert.DeserializeObject<string[]>(ids);
}

How to add/remove element in list on the basis of selection of 2 dropdown list in multi select bootstrap dropdown jquery?

Hope all of you fine and doing well.
I am using multi select bootstrap drop down jquery. I am using asp.net core to populdate Listbox, its working fine for selection,select all etc.
But i want that when i select element from Dropdown A then this element must be removed from dropdown B and if i unselect element from dropdown A then it must added/show in dropdownB. And vice virsa as well, if element selected in dropdown B then this element removed from dropdownA, also if select all from dropdownA then all elements removed from dropdownB and vice virsa as well.
Hope you understand guys.
For example: If A,B,C,D values in dropdownlistA and if i select A then it must be disable or hide from dropdownB,if i select all then must remove all from dropdownB, and also vice virsa for dropdownB as well,
Note: DropdownA and DropdownB both have same number of values/elements,same text ,same value,
View
#section AddToHead{
<link rel="stylesheet" href="~/css1/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="~/css1/bootstrap-multiselect.css" type="text/css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="~/js1/bootstrap-2.3.2.min.js"></script>
<script type="text/javascript" src="~/js1/bootstrap-multiselect.js"></script>
}
<form class="column" asp-controller="group" asp-action="createresult" style="height:100%;" method="post">
<span class="column" style="height:50px;">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamA", onChange = "getSelectedOptions(this)", multiple = "multiple" })
#Html.ValidationMessageFor(model => model.TeamOnePlayers)
</span>
<span class="column">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamB", onChange = "getSelectedOptions(this)", multiple = "multiple" })
#Html.ValidationMessageFor(model => model.TeamTwoPlayers)
</span>
</form>
</div>
#section Scripts {
<script type="text/javascript">
$(function () {
$('#PlayersTeamA').multiselect({
includeSelectAllOption: true
});
$('#PlayersTeamB').multiselect({
includeSelectAllOption: true
});
});
function getSelectedOptions(sel) {
var idddl = sel.id;
var opts = [],
opt;
var len = sel.options.length;
for (var i = 0; i < len; i++) {
opt = sel.options[i];
if (opt.selected) {
opts.push(opt);
var idul = sel.id;
alert(idul);
var ul = document.getElementById(idul);
ul.removeChild(ul.childNodes[1]);
}
}
return opts;
}
Here is a working demo like below:
#model Players
<form class="column" asp-controller="group" asp-action="createresult" style="height:100%;" method="post">
<div id="A">
<span class="column" style="height:50px;">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamA", multiple = "multiple" })
</span>
</div>
<div id="B">
<span class="column">
#Html.ListBoxFor(x => x.AvailablePlayers, Model.AvailablePlayers, new { id = "PlayersTeamB", multiple = "multiple" })
</span>
</div>
</form>
#section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css"/>
<script>
$(function () {
$('#PlayersTeamA').multiselect({
includeSelectAllOption: true
});
$('#PlayersTeamB').multiselect({
includeSelectAllOption: true
});
});
var data = [];
$('#B option').each(function (index, item) {
data.push({ label: this.label, value: this.value });
});
$("#PlayersTeamA").change(function () {
var selectedText = $('#PlayersTeamA').val();
var newData = data;
selectedText.forEach(function (element, index, array) {
newData = newData.filter(function (el) { return el.value != element; });
});
$("#PlayersTeamB").multiselect('dataprovider', newData);
});
</script>
}
My testing model:
public class Players
{
public SelectList AvailablePlayers { get; set; }
}
public class AvailablePlayer
{
public int Id { get; set; }
public string Name { get; set; }
}
My testing controller:
[HttpGet]
public async Task<IActionResult> Index()
{
var player = new List<AvailablePlayer>()
{
new AvailablePlayer(){ Id=1,Name="aa"},
new AvailablePlayer(){ Id=2,Name="bb"},
new AvailablePlayer(){ Id=3,Name="cc"}
};
var model = new Players()
{
AvailablePlayers = new SelectList(player, "Id", "Name")
};
return View(model);
}
Result:
It appears you are using bootstrap's multiselect. In the documentation, we can see that you can configure data as follows (after executing .multiselect on particular input, as you do in your sample):
var data = [
{label: "Messi", value: "Messi"},
{label: "Ronaldo", value: "Ronaldo"}
];
$("#PlayersTeamA").multiselect('dataprovider', data);
Now, attach to 'onchange' event of #PlayersTeamA and update the available data for #PlayersTeamB, for example like this:
$("#PlayersTeamA").change(function () {
var selectedText = $(this).find("option:selected").text();
var newData = data.filter(function(el) { return el.value == selectedText; });
$("#PlayersTeamB").multiselect('dataprovider', newData);
});
You have to attach to onchange of #PlayersTeamB as well, I believe (so that it works in both directions).

Getting values on particular index in javascript

I have a button and onclick of that button, i am running a AJAX call and getting values from another jsp page. My rows are indexed.
<%
List<DiskSheet> ds1 = new ArrayList<DiskSheet>();
if (request.getParameter("numLLP") != null && !request.getParameter("numLLP").isEmpty()) {
int numLLP = Integer.valueOf(request.getParameter("numLLP"));
for (int i=0;i<numLLP;i++) {
DiskSheet d = new DiskSheet();
d.setCH5Limiter(request.getParameter("limiter_"+i));
d.setMfrPrice(request.getParameter("diskvalues_"+i));
d.setDiskCyc(request.getParameter("diskcyc"));
ds1.add(d);
}
request.getSession().setAttribute("engine" + request.getParameter("diskid"), ds1);
}
<%
List<DiskSheet> ds = (List<DiskSheet>) request.getSession().getAttribute("engine" + request.getParameter("diskid"));
if (ds == null) {
ds = new ArrayList<DiskSheet>();
}
String disksheet = request.getParameter("disksheet");
if (disksheet != "") {
String engine = request.getParameter("Engines");
if (ds.size() == 0) {
ds = DiskSheet.getLLPEngine(engine);
}
%>
<div><input type="text" style="text-align:right;" name="limiter_<%=i%>" id="limiter" class="limiter" value="<%=airs.getCH5Limiter()%>" size="10" onblur="getDiskSheetCyc()"></div>
<div><input type="hidden" class="diskvalues" id="diskvalues" name="diskvalues_<%=i%>" size="10" value="<%=airs.getMfrPrice()%>" onblur="getDiskSheetCyc()"></div>
<div><input type="text" class="diskcyc" id="diskcyc" name="diskcyc" size="10" value="<%=airs.getDiskCyc()%>" onblur="getDiskSheetCyc()"></div>
I am trying to perform a simple calculation and print the values in the third row however, it only displays the value in one of the cells. Here's what i tried.
function showPopup(diskid){
document.getElementById("popup_win").style.display = 'block';
}
function getDiskSheet(diskid) {
var form = document.getElementById("airplaneForm");
var id = diskid;
var myAjax = new Ajax.Updater("ch5limiteroutput",
"/jsp/Ch5Limiter.jsp", {
asynchronous : true,
postBody : Form.serialize(form),
data: id,
method : 'post',
onComplete : function() {
displayLimiter();
getDiskSheetCyc();
document.getElementById("id").innerHTML = id;
}
});
}
function displayLimiter() {
var form = document.getElementById("airplaneForm");
var limiteroutput = document.getElementById("ch5limiteroutput").innerHTML;
document.getElementById("limiter").innerHTML = limiteroutput;
}
function getDiskSheetCyc(){
var diskvalues = document.getElementsByClassName("diskvalues");
var limiter = document.getElementsByClassName("limiter");
for (var i = 0; i < diskvalues.length; i++) {
var diskval = parseInt(diskvalues[i].value);
var limiter = parseInt(limiter[i].value);
diskcyc = diskval/limiter;
}
document.getElementById('diskcyc').value = diskcyc;
}
<td class="trigger_popup" ><input type="button" id="1" value="Disk Sheet" name="disksheet" class="disksheet" onclick="showPopup(this.id);getDiskSheet(this.id);">
</td>
<div class="popup_win" id="popup_win">
<span class="helper"></span>
<div>
<br>
<div id="TableBox" class="TableBox" style="width: 110%;">
<div>
<div><span class="id" id="id"></span></div>
<div><span class="limiter" id="limiter"></span></div>
</div>
</div>
</div>
</div>
<div id="ch5limiteroutput" style="display: none"></div>
Also tried doing it through jQuery but it doesn't seem to go inside the loop. I am not sure what i am doing wrong here. Any help is greatly appreciated. Thank you.
function getDiskSheetCyc(){
const jQuerytable = jQuery('#TableBox');
const jQueryrow = jQuerytable.find('> div');
jQuery(".jQueryrow").each(function() {
const jQuerythis = jQuery(this);
const diskvalues = parseInt(jQuerythis.find('.diskvalues').val());
const limiter = parseInt(jQuerythis.find('.limiter').val());
const diskcyc = diskvalues/limiter;
if (!isNaN(diskcyc)) jQuerythis.find('.diskcyc').val(diskcyc);
});
}
Your code at present does not make a lot of sense. For a jQuery solution, consider the following code example.
$(function() {
function showPopup() {
$("#popup_win").show();
}
function displayLimiter() {
var limiteroutput = $("#ch5limiteroutput").html();
$("#limiter").html(limiteroutput);
}
function getDiskSheetCyc() {
var diskvalues = $(".diskvalues");
var limiter = $(".limiter");
var diskcyc = 0;
diskvalues.each(function(i, el) {
var diskval = $(el).val() == "" ? parseInt($(el).val()) : 0;
var limiter = $(el).val() == "" ? parseInt($(el).val()) : 0;
if (diskval > limiter) {
diskcyc = diskval / limiter;
}
});
$('#diskcyc').val(diskcyc);
}
function getDiskSheet(diskid) {
var form = $("#airplaneForm");
var id = diskid;
$.post("/jsp/Ch5Limiter.jsp", {
postBody: form.serialize(),
data: id
}, function(results) {
displayLimiter();
getDiskSheetCyc();
$("#id").val(id);
});
}
$("[type='button']").click(function() {
showPopup();
getDiskSheet($(this).attr("id"));
});
});
.popup {
border: 1px solid #ccc;
border-radius: 6px;
width: 340px;
height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td class="trigger_popup">
<input type="button" id="1" value="Disk Sheet" name="disksheet" class="disksheet">
</td>
</tr>
</table>
<div class="popup window" id="popup_win" style="display: none;">
<span class="helper"></span>
<div>
<br>
<div id="TableBox" class="TableBox" style="width: 110%;">
<div>
<div><span class="id" id="id"></span></div>
<div><span class="limiter" id="limiter"></span></div>
</div>
</div>
</div>
</div>
<div id="ch5limiteroutput" style="display: none"></div>
So this encounters issues all over due to a number of missing elements that were not provided. The basic idea is you want to show a popup, post some data, and then update some content. I don't see where you do anything with data returned from the AJAX call... I am guessing it's just updating the DB with no feedback.
It would be helpful to provide an example of the data that is retuened if you need more help there.
In regards to the calculation, you're on the right path. You just need to make sure the proper fields get populated with the right details. I am assuming this is where the data from the POST gets to be used.
Examine your Network tab in development tools. You should see the POST action, the Headers, and the Response. This should help you identify if you're getting an error in your AJAX or maybe getting different data back than expected.

Dropdown list not showing the saved value after page reload

I have a dropdownlist for Page location with 2 values. When I select a value from the list and click on Save, the value is saved in the database. But when I reload the page, the value which is first in the selection criteria is shown and when I edit other values and click on Save, the value for Page location is also changed. The issue is, I want to see the value which I changed for the Page location when the page is refreshed. Below is my code. Function 'edit' is called when I click on edit of the Page location.
HTML Code:
<script id="editTemplate" type="text/x-kendo-template">
<div class = "row">
<div class="col-sm-8">
<label style="display:none;">Id:</label>
<input type="hidden" id='ID' class="k-textbox" value="#=node.id #" />
</div>
<div class="col-sm-8">
<label >PageLocation:</label>
<select id = "pl">
<option value="local">local</option>
<option value="New Window" >New Window</option>
</select>
</div>
<div class="col-sm-4">
<button id="save" class="k-button k-primary">Save</button>
</div>
</div>
JavaScript:
function edit(itemid){
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node}))
.appendTo("body")
.kendoWindow({
modal: true,
deactivate: function () {
this.destroy();
}
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var Id = $('#ID').val();
var PageLocation = $('#pl').val();
node.text = undefined;
node.set("Pagelocation", PageLocation);
node.set("id", Id);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("Pagelocation", PageLocation);
treenode.set("id", Id);
treenode.PAGE_LOCATION = PageLocation;
treenode.ID = Id;
$.ajax({
url: "/Services/TreeServices.asmx/UpdateTree",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
//data: JSON.stringify({ "erpLinksJson": treenode, NodeId: nid, RoleId: rid })
data: JSON.stringify({ "LinksJson": treenode})
});
console.log(JSON.stringify(treenode));
})
}
Service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String UpdateTree(LinksJSON LinksJson)
{
using (var context = new Data.WebEntities())
{
context.Configuration.ProxyCreationEnabled = false;
var updNode = context.Links.Where(c => c.ID == LinksJson.ID).FirstOrDefault();
if (updNode != null)
{
updNode.ID = erpLinksJson.ID;
updNode.PAGE_LOCATION = erpLinksJson.PAGE_LOCATION;
context.SaveChanges();
}
JavaScriptSerializer JSON = new JavaScriptSerializer();
return JSON.Serialize(updNode);
}
}

Categories

Resources