#Html.DropDownList("GroupCode",(IEnumerable<SelectListItem>)ViewBag.GroupCode,"-- Please Select --", new{#id="groupcd"})
DropDownList to select group and post back the value selected to JSON to get a list of clientcode and put into another DropDownList
$(function() {
$("#groupcd").change(function () {
var selectedValue = $("#groupcd").val();
$.post('#Url.Action("getClientCD", "OutstandingClaim")', { selection: selectedValue }, function (data) {
$("#clientcd").html(data);
});
});
});
Javascript to get the selected value and post to action
public JsonResult getClientCD(string selection)
{
var data = db.Common_CustMas.Where(c => c.Group == selection)
.ToList().Select(x => string.Format("{0}--{1}", x.CUSTCODE, x.CUSTNAME));
ViewBag.ClientCode = data;
return Json(data, JsonRequestBehavior.AllowGet);
}
after post back to controller, query the list out and pass back
#Html.DropDownList("ClientCD", (IEnumerable<SelectListItem>) ViewBag.ClientCode, "--Please Select --", new{#id="clientcd"})
The query works, but no data was passed back to the ViewBag client code. Anyone know what problem and how to solve this?
you can do this way
$('#CityID').change(function () {
var cityid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDistrictsList ","Controller")',
data: { CityID: cityid },
datatype: "json",
success: function (data) {
var ddldist = $('#DistrictID');
$.each(data, function (val, text) {
ddldist.append(
$('<option></option>').val(val).html(text)
);
});
},
})
});
finally it solved with the code
$(function() {
$("#groupcd").change(function () {
var selectedValue = $("#groupcd").val();
$.getJSON('#Url.Action("getClientCD", "OutstandingClaim")', { selection: selectedValue }, function (result) {
var ddl = $('#clientcd');
ddl.empty();
$(result).each(function () {
ddl.append(
$('<option/>').html(this.Text)
);
});
});
});
});
controller
public JsonResult getClientCD(string selection)
{
var data = (from a in db.Common_CustMas
where a.Group == selection
select new {Text = ( a.CUSTCODE + "-" + a.CUSTNAME)}).Distinct().ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
dropdownlist
#Html.DropDownList("GroupCode",(IEnumerable<SelectListItem>)ViewBag.GroupCode,"-- Please Select --", new{#id="groupcd"})
#Html.DropDownList("ClientCD", new SelectList(Enumerable.Empty<SelectListItem>()),new{#id="clientcd"})
Related
I'm working on a ASP .Net Core project where for the first time I'm using Select2.
I have one page where I'm passing the ID's that I need by ViewModel like this:
Controller:
public async Task<IActionResult> MyPage()
{
var model = new MyViewModel()
{
selectedUSerId = 1,
selectedEmployeeId =1
};
return View(model);
}
View:
#model MyViewModel
<select class="form-select" id="User" name="User" data-url="#Url.Action("MyUserAction","MyUserController")" data-placeholder="#Localizer["SelectUser"].Value">
<option></option>
</select>
<select class="form-select" id="Employee" name="Employee" data-url="#Url.Action("MyEmployee","MyEmployeeController")" data-placeholder="#Localizer["SelectUser"].Value">
<option></option>
</select>
#section Scripts{
<script type="text/javascript">
var userId = "#Model.selectedUSerId";
var emplyeeId = "#Model.selectedEmployeeId";
$(document).ready(function () {
$('select').each(function () {
InitSelect2(this.id);
});
if(userId){
$('#User').val(userId).trigger('change');
}
if(emplyeeId){
$('#User').val(emplyeeId).trigger('change');
}
});
function InitSelect2(selector, selectedId = 0) {
var url = $("#" + selector).data('url');
var placeholder = $("#" + selector).data('placeholder');
const type = "POST";
const dataType = "json";
if (!url) {
console.error("Selector: " + selector + " Unspecified URL");
return;
}
if (placeholder === "") {
console.error("Selector: " + selector + " Unspecified Placeholder");
return;
}
try {
$("#" + selector).select2({
theme: "bootstrap-5",
width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
placeholder: placeholder,
allowClear: true,
minimumInputLength: 3,
ajax: {
url: url,
type: type,
dataType: dataType,
delay: 250,
data: function (params) {
var query = {
id: selectedId,
searchFullName: params.term,
}
return query;
},
processResults: function (data) {
console.log(data)
return {
results: data.results
};
},
}
})
} catch (ex) {
console.error(ex);
}
}
</script>
}
So far it works perfectly.
But when I try to do:
$('#User').val(userId).trigger('change'); or
$('#Employee').val(emplyeeId ).trigger('change');
nothing happened.
I think its gonna work only when I retrieve the data the first time when I click the drop donw list, instead of doing it every time when it is clicked.
In that way I will have the <option>s and I can use the jQuery to select the <option> by Id.
I don't like to follow this approach, becouse the data should be load and setted dynamically. Theres no another way to do it?
If you want to do something only when first time the selected value is changed,you can try to use a js variable,change the value of it when first time the selected value is changed.Here is a sample,only when first time the selected value is changed,alert(1) will be called.
var UserCount = 0;
var EmplyeeCount = 0;
$('#User').change(function() {
if (UserCount == 0) {
UserCount++;
alert(1);
}
});
$('#Employee').change(function() {
if (EmplyeeCount == 0) {
EmplyeeCount++;
alert(1);
}
});
I stucked on one thing. I have a 2 grid inside checkboxes. When I selected that checkboxes I want to POST that row data values like array or List. Actually when i send one list item it's posting without error but when i get more than one item it couldn't post values.
Example of my grid
Here my ajax request and how to select row values function
var grid = $("#InvoceGrid").data('kendoGrid');
var sel = $("input:checked", grid.tbody).closest("tr");
var items = [];
$.each(sel, function (idx, row) {
var item = grid.dataItem(row);
items.push(item);
});
var grid1 = $("#DeliveryGrid").data('kendoGrid');
var sel1 = $("input:checked", grid1.tbody).closest("tr");
var items1 = [];
$.each(sel1, function (idx, row) {
var item1 = grid1.dataItem(row);
items1.push(item1);
});
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
data: JSON.stringify({ 'items': items, 'items1': items1, 'refnum': refnum }),
contentType: 'application/json',
traditional: true,
success: function (msg) {
if (msg == "0") {
$("#lblMessageInvoice").text("Invoices have been created.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
var del1 = $("#InvoiceDetail").data("kendoWindow");
del1.center().close();
$("#grdDlvInv").data('kendoGrid').dataSource.read();
}
else {
$("#lblMessageInvoice").text("Problem occured. Please try again later.")
var del = $("#InvoiceOKWindow").data("kendoWindow");
del.center().open();
return false;
}
}
});
This is my C# part
[HttpPost]
public string CreateInvoice(List<Pm_I_GecisTo_Result> items, List<Pm_I_GecisFrom_Result> items1, string refnum)
{
try
{
if (items != null && items1 != null)
{
//do Something
}
else
{
Log.append("Items not selected", 50);
return "-1";
}
}
catch (Exception ex)
{
Log.append("Exception in Create Invoice action of HeadOfficeController " + ex.ToString(), 50);
return "-1";
}
}
But when i send just one row it works but when i try to send more than one value it post null and create problem
How can i solve this? Do you have any idea?
EDIT
I forgot to say but this way is working on localy but when i update server is not working proper.
$.ajax({
url: '../HeadOffice/CreateInvoice',
type: 'POST',
async: false,
data: { items: items, items1: items1 }
success: function (msg) {
//add codes
},
error: function () {
location.reload();
}
});
try to call controller by this method :)
I am getting value in Column , following is the code.
grid.Column(columnName: "Name", header: "Name",format: #<text>
<span id="Name">#item.Name</span></text>, canSort: false),
want to use this value in function which I have called on delete button
function DeleteEnterpriseID() {
var checkID = $(".edit-mode:checked").map(function () {
return this.value;
}).toArray();
alert(checkID.join(","));
if (confirm("Are you sure you want to delete?") == true) {
var url = "#Url.Action("DeleteEnterpriseIdDetails")";
var pname = $('#Name').val(); //// Here I want that value from the clicked row so that I can pass that to controller.
alert(pname);
$.ajaxSetup({ cache: false });
$.post(url, { Pname: pname, EnterpriseID: checkID.join(",") })
.success(function (response) {
if (response != null && response.success) {
alert(response.responseText);
window.location.href = response.newurl;
} else {
alert(response.responseText);
}
})
.error(function (response) { alert("error"); });
}
else {
return false;
}
}
But I am getting blank value for Name from clicked row.
Kindly assist.
It should be:
var pname = $('#Name').text();
Because its a span tag and not an input element. val() works for input elements.
I am still learning jQuery/json and am struggling to figure out how to include optgroups when building my DropDownList via jQuery using json data.
Here is an example of the json data:
0:
Disabled: false
Group:
Disabled: false
Name: "Property Overview"
Selected: false
Text: "Number of Floors"
Value: "277"
Currently, I am able to populate the DropDownList with the Text and Value. That is fairly straight forward. Here is my code for that:
$(document).ready(function () {
$("#PropertyList").on('change', function () {
$("#Options_Question").empty();
var id = $("#PropertyList").val();
var url = '#Url.Action("GetPropertyTypeSpecificQuestions", "Report", new { id = "replaceToken" })';
url = url.replace("replaceToken", id);
$.getJSON(url, null, function (data) {
$("#Options_Question").addQuestions(data);
});
});
$.fn.addQuestions = function (data) {
return this.each(function () {
var list = this;
$.each(data, function (index, questionData) {
var option = new Option(questionData.Text, questionData.Value);
list.add(option);
});
});
}
});
How can I edit my jQuery to include the values from Group.Name and group the questions into their respective optgroups?
I was able to get this working using information found in various places around stackoverflow. Here is the working jQuery:
$(document).ready(function () {
$("#PropertyList").on('change', function () {
$("#Options_Question").empty();
var id = $("#PropertyList").val();
var url = '#Url.Action("GetPropertyTypeSpecificQuestions", "Report", new { id = "replaceToken" })';
url = url.replace("replaceToken", id);
$.getJSON(url, null, function (data) {
$("#Options_Question").addQuestions(data);
});
});
$.fn.addQuestions = function (data) {
var prevGroup, prevGroupName;
$.each(data, function () {
if (this.Group.Name == null) {
$("<option />").val(this.Value).text(this.Text).appendTo("#Options_Question");
}
else if (prevGroupName != this.Group.Name) {
prevGroup = $('<optgroup />').prop('label', this.Group.Name).appendTo('#Options_Question');
}
$("<option />").val(this.Value).text(this.Text).appendTo(prevGroup);
prevGroupName = this.Group.Name;
});
}
});
I have a simple controller like this:
public JsonResult GetPosts(int? id)
{
var varid = id;
var ret = (from post in db.Posts.ToList()
orderby post.PostedDate descending
select new
{
NeighbourhoodId = varid,
Message = post.Message,
PostedByName = post.ApplicationUser.UserName,
PostedDate = post.PostedDate.ToString(),
PostId = post.PostId,
});
return Json(ret, JsonRequestBehavior.AllowGet);
}
Here, i am able to get the dropdown selected value.I am assigning it to a variable varid and then assigning it to NeighbourhoodId.
But, when the view page is rendered nothing changes all the 4 Post are showing.but in reality it should display only 2 Post.
This is my view page code:
<ul id="msgHolder" data-bind="foreach: posts">
<li class="postHolder">
<p><a data-bind="text: PostedByName"></a>: <span data-bind=" html: Message"></span></p>
and my wallpost.js file in script folder where all knockout view model related code is here.It first loads all the Post from database correctly but data doesnot get filtered if i am trying to filter it with dropdown change.
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.NeighbourhoodId = data.NeighbourhoodId;
self.Message = ko.observable(data.Message || "");
self.PostedByName = data.PostedByName || "";
self.PostedDate = getTimeAgo(data.PostedDate);
self.error = ko.observable();
function viewModel() {
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
self.loadPosts = function () {
// to load existing posts
$.ajax({
url: postApiUrl,
datatype: "json",
contentType: "application/json",
cache: false,
type: 'Get'
})
.done(function (data) {
var mappedPosts = $.map(data, function (item)
{ return new Post(item); });
self.posts(mappedPosts);
})
.fail(function () {
error('unable to load posts');
});
}
return self;
};
ko.applyBindings(new viewModel());
and my dropdown related code is here:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList,"Select a Location")
<script type="text/javascript">
$(document).ready(function () {
$("#Locations").change(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("GetPosts", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
When i debug, i am getting correct id value in controller but there is problem in filtering out data. Is there a need for some change in knockout file.what to do here ??
Instead of mixing jquery event handlers and knockout bindings, i think it's better for you handle all with knockout.
Bind your select element (drop down) with the options binding and load the locations array on view model initialization; bind the value to a observable property, ex: 'CurrentLocation'
Subscribe to the change of the property 'CurrentLocation', ex:
myViewModel.CurrentLocation.subscribe(function(newValue) {
//request to GetPosts here
});
On .done() function of the GetPosts request update the observableArray with the items received by the server
Hope this helps!
UPDATE
The following is a very simple example, i changed my mind and used "event" binding to handle the change event instead of "options" binding but the concept it's the same.
#Html.DropDownList("Locations", new SelectList(Model.Locations, "Id", "Name"), new { data_bind = "event: { change: reloadPosts}" })
<ul data-bind="foreach: posts">
<li data-bind="text:CompleteText"></li>
</ul>
<script>
function Post(data) {
var self = this;
self.Id = ko.observable(data.Id);
self.LocationId = ko.observable(data.LocationId);
self.Text = ko.observable(data.Text);
self.CompleteText = ko.computed(function () {
return self.Id() + " " + self.Text();
});
}
function PageViewModel() {
var self = this;
self.posts = ko.observableArray();
self.reloadPosts = function () {
$.ajax({
type:"POST",
url: "GetPosts",
data: { locationId: $("#Locations").val() }
}).done(function (data) {
var mappedPosts = $.map(data, function (item)
{ return new Post(item); });
self.posts(mappedPosts);
});
}
}
var vm = new PageViewModel();
ko.applyBindings(vm);
</script>
The GetPosts method in the controller:
[HttpPost]
public JsonResult GetPosts(string locationId)
{
var selectedPosts = posts.Where(x => x.LocationId == locationId);
return Json(selectedPosts, JsonRequestBehavior.AllowGet);
}
The posts collection in the controller in the example above it's just an inmemory collection, probably you will read it from a DB or something like that.
The post class on the c# code:
class Post
{
public string Id { get; set; }
public string LocationId { get; set; }
public string Text { get; set; }
}
And finally the viewmodel used:
public class TestViewModel
{
public List<Location> Locations { get; set; }
}