I am trying to get the dynamically created TextBox ID into jQuery from Razor view. The IDs are created in HTML as follows:
Product - 1: cartDetails_0__Quantity
Product - 2: cartDetails_1__Quantity
Right now, when I give the above inputs directly to Ajax call, it updates the corresponding rows. As an example:
#if (ViewBag.Cart != null)
{
for (int i = 0; i < cartDetails.Count(); i++)
{
<tr>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Id)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].IP)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].ProductName)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Price)</td>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Quantity, new { #class = "quantityUpdate", data_id = cartDetails[i].Id })</td>
</tr>
}
}
var url = '#Url.Action("UpdateCart2")';
$(".quantityUpdate").change(function () {
var id = $(this).data('id');
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $('#cartDetails_' + 0 + '__Quantity').val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
alert($('#cartDetails_' + 0 + '__Quantity').val());
});
Is there any way to loop through jQuery to get the dynamically generated TextBox ID in Razor? I've tried the following but doesn't get the value:
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $('#cartDetails_' + i + '__Quantity').val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
Even tried this one but it gets the value of first TextBox only:
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $(this).val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
Note: I am trying to update rows giving input to the TextBoxes with Ajax call. The TextBoxes are in a loop in the view. In this regards, I've to get the IDs of the dynamically generated HTML IDs.
You can use create event of dynamically created elements in order to get their Ids.
But bear in mind to use this you need to use On(). See http://api.jquery.com/on/
See also:
Event binding on dynamically created elements?
In jQuery, how to attach events to dynamic html elements?
PS. If there is a cleaner way to get dynamically created elements I would also be glad to get it :)
Edit. Maybe I was not clear enough . There is no exactly "create" event. You just can hook any actions you need to On()
See also jQuery "on create" event for dynamically-created elements
Related
I am new and struggling to find a way to create a searchable dropdownlist (MVC5/C#). I have tried Select2, and could not get it working. I am desperate and out of time.
Looking at a few tutorials on Jquery Autocomplete, it seems pretty straight and forward. My problem is that all of the examples on line seems to use static data. My dropdownlist is populated from my Controller using a List of pre-filtered results.
This is how I populate my doprdownlist
List<SelectListItem> autocomplete = db.ICS_Supplies.Where(s => s.InvType == "F").Select(x => new SelectListItem { Value = x.Supplies_ID.ToString(), Text = x.Old_ItemID + " " + " | " + " " + " Description: " + x.ItemDescription, Selected = false }).DistinctBy(p => p.Text).OrderBy(p => p.Text).ToList();
ViewBag.FormsList = new SelectList(autocomplete, "Value", "Text");
As is, the dropdown populates - but it has a lot of records and is VERY slow.
From most of the examples I have seen online, the searchable items are something like:
var options = [
{ value: 'Adam', data: 'AD' },
// ...
{ value: 'Tim', data: 'TM' }
];
That's great, if I want to type out a thousand possible items - but I need to populate my DropDownList options from a table. .. and I am lost.
I am very new to Jquery and any direction is greatly appreciated.
EDIT1*
I am adding the View Code (from the online Example) for more clarification
<div class="form-group col-sm-5">
<label for="files">Select Supply:</label>
<input type="text" name="supplies" id="autocomplete" />
</div>
<div>
Selected Option : <span class="label label-default" id="selected_option"></span>
</div>
I suggest you need ajax to get a dynamic autocomplete list. Here's some sample code - it's the definition of a basic jQuery implementation that uses ajax.
function close_autocomplete($elemid) {
jQuery($elemid).autocomplete("destroy" );
}
function attach_autocomplete($elemid) {
jQuery($elemid)
.autocomplete({
delay : 250,
minLength : 3,
source : function( request, response ) {
var $thedata = request.term;
jQuery.ajax({
url : myajaxresponder.php,
type : "GET",
data : {
action_id : "autocomplete",
thedata : $thedata
},
error : function (jqXHR, textStatus, errorThrown){
console.log(textStatus + " " + errorThrown);
response("");
},
success : function (result) {
var resultarray = JSON.parse(result);
response(resultarray);
}
});
},
select : function ( event, ui ) {
jQuery($elemid).val(ui.item.value);
return false;
},
})
}
// attach the handlers
jQuery("#myid").focus(function ()
{attach_autocomplete(jQuery(this).prop("id"))});
jQuery("#myid").blur(function ()
{close_autocomplete(jQuery(this).prop("id"))});
I have a problem in updating sql database table with jQuery ajax.
here is my scenario. I am working on privileges table to assign a teacher some kind of privilege/rights to perform some required functionality of the website.
1) I call a webmethod and pass teacher's id to retrive all privileges assigned to that particular teacher using jQuery ajax
2) in the success function of step 1 I call another web method using jQuery ajax and bind a click event on checkbox (on/of toggle button -- its input type was checkbox) present against every privilege listed.
3) when I click on that on/off toggle checkbox I want to update a row in sql database table in privileges table if it is on and user turns it off then that particular privilege will be unassigned to that teacher.
here is my code
public void UpdatePrivileges(string _columnName, byte _value, int _teacherid)
{
JavaScriptSerializer objserializer = new JavaScriptSerializer();
myDatabase.CreateConnection();
myDatabase.InitializeSQLCommandObject(myDatabase.GetCurrentConnection, "update tbl_privileges set " + _columnName + " = #val where teacher_id = #tid");
myDatabase.obj_sqlcommand.Parameters.AddWithValue("#tid", _teacherid);
myDatabase.obj_sqlcommand.Parameters.AddWithValue("#val", Convert.ToByte(_value));
try
{
myDatabase.OpenConnection();
myDatabase.obj_sqlcommand.ExecuteNonQuery();
}
finally
{
myDatabase.CloseConnection();
myDatabase.obj_sqlcommand.Dispose();
}
HttpContext.Current.Response.Write(objserializer.Serialize("Updated"));
}
This code is for retrieving teacher's privileges and show them on webForm.
function GetTeacherPrivileges() {
var teacherid = $('#<%=txtTeacherIDToPopulatePrivileges.ClientID%>').val();
$.ajax({
url: 'source/WebServices/GetAllTeachers.asmx/GetPrivileges',
method: 'post',
data: { _teacherID: teacherid},
datatype: 'json',
success: function (data) {
var obj = JSON.stringify(data);
var arrayjson = $.parseJSON(obj);
var actualarray = $.parseJSON(arrayjson);
$.each(actualarray, function (i, v) {
$('#tablebody').append('<tr class="table-row"> <td class="col-3"><span>Events</span></td><td class="col-2">is this teacher eligible to making events?</td><td class="col-3"><label class="switch centerbuttion "><input id="check_event" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="No"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"> <td class="col-3"><span>Attendance</span></td><td class="col-2">Do you want this teacher can mark attendance?</td><td class="col-3"><label class="switch centerbuttion "><input id="check_attendance" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Homework</span></td><td class="col-2">Teacher will be able to upload homework with their respective classes.</td><td class="col-3"><label class="switch centerbuttion "><input id="check_homework" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Reports</span></td><td class="col-2">Do you want this teacher to generate reports?</td><td class="col-3"><label class="switch centerbuttion "><input id="check_reports" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Timetable</span></td><td class="col-2">Can this teacher make time table(s)?</td><td class="col-3"><label class="switch centerbuttion "><input id="check_timetable" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Datesheet</span></td><td class="col-2">Can this teacher make Date Sheet(s)?</td><td class="col-3"><label class="switch centerbuttion "><input id="check_datesheets" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr>');
var event = v.Event;
var attendance = v.Attendance;
var homework = v.Homework;
var reports = v.Reports;
var timetable = v.TimeTable;
var datesheet = v.DateSheet;
if (event == 1) {
$('#check_event').trigger('click');
}
if (attendance == 1) {
$('#check_attendence').trigger('click');
}
if (homework == 1) {
$('#check_homework').trigger('click');
}
if (reports == 1) {
$('#check_reports').trigger('click');
}
if (timetable == 1) {
$('#check_timetable').trigger('click');
}
if (datesheet == 1) {
$('#check_datesheets').trigger('click');
}
$('#check_event').bind({
click: function () {
var privilegevalue = columnvalue('#check_event');
UpdatePrivilege('event', privilegevalue);
}
});
});
},
error: function (error) {
alert("Error: " + error);
}
});
This is the second AJAX code which I call in the success function of above AJAX for binding the click event.
function UpdatePrivilege(column,value) {
var teacherid = $('#<%=txtTeacherIDToPopulatePrivileges.ClientID%>').val();
$.ajax({
url: 'source/WebServices/GetAllTeachers.asmx/UpdatePrivileges',
data: { _columnName: "'"+column+"'" , _value: value , _teacherid:teacherid },
dataType: 'json',
dataContent: 'application/json; charset=utf-8',
success: function (data) {
alert('privilege updated'+data);
},
error: function(data) {
alert('Error in updating privilege' + data);
}
});
}
When I run my aspx page and input teacher's id to GetAllTeachers() function all works good and it binds the click event on checkbox against event privilege but when I click on that it gives me error from AJAX function of UpdatePrivilege() function.
If you are wanting to send json you need to stringify the data yourself. Also you don't need the extra quotes wrapping "'"+column+"'"
Try:
function UpdatePrivilege(column,value) {
// I assume you are running this within Razor context and not in a javascript file
var teacherid = $('#<%=txtTeacherIDToPopulatePrivileges.ClientID%>').val();
// create data object
var dataObj={ _columnName: column , _value: value , _teacherid:teacherid };
// stringify it
var postData = JSON.stringify(dataObj);
$.ajax({
url: 'source/WebServices/GetAllTeachers.asmx/UpdatePrivileges',
data: postData ,// stringified data
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log('privilege updated', data);
},
error: function(data) {
console.log('Error in updating privilege' , data);
}
});
}
I'm working on a View which has a List (Selected bool / ID string / Name string / Value decimal).
In this view user will select some items and submit form to save them in a database. But this List/ has approximately 2000 items and it is extremely slow.
My Controller:
public ActionResult Create(List<MyClass> list) {
foreach (var item in list) {
if (item.Checked) {
// something
}
}
}
My View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#* TH /HTML *#
#for (int r = 0; r < Model.Count(); r++)
{
<tr class="tr-clickable">
#Html.HiddenFor(i => i[r].ID_User)
<td>#Html.CheckBoxFor(i => i[r].Checked)</td>
<td>#Html.DisplayFor(i => i[r].Anything1)</td>
<td>#Html.DisplayFor(i => i[r].Anything2)</td>
<td>#Html.DisplayFor(i => i[r].Value)</td>
</tr>
}
#* HTML *#
<div class="control-group margin-top-20 pull-right">
<div class="controls">
<input type="submit" class="btn btn-default" value="Send Form" />
</div>
</div>
}
Is there a better way to receive this List in my controller? I've been thinking to send list by jQuery-ajax and saving them one by one.
What do you guys think about it?
I think, your problem is not in "passing the list" but in "saving selected list items one by one". Sending 2k list from view to controller is not that heavy (well, it is, but it should still work not too slow). But if you perform N database operations for N selected items, this is where you have your bottle neck.
You have 2 options:
Save selected item as soon as user selects it.
Optimize your database operations by at least using single transaction for saving items.
As others have mentioned, I would first explore changing the entire user experience. If you are indeed in a situation where the user needs to select a large quantity of records one by one, I would use AJAX and submit them to a web api controller one by one as they're selected.
This has the added benefit of progressively saving progress and allowing the user to step away from the screen.
My solution was in jQuery Ajax:
$('input[type="button"][data-submit]').click(function () {
if (confirm('Anything?')) {
var array = [];
$('#table > tbody > tr').each(function () {
var $tr = $(this);
var usid = $tr.find('[data-usid]').val();
var irvlr = $tr.find('[data-irvlr]').val();
array.push({
User: usid,
Value: irvlr
});
});
if (array.length > 0) {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("MyAction", "MyController")',
data: JSON.stringify({ 'list': array }),
success: function (result) {
window.location.href = result.url;
},
error: function (ex) {
}
});
}
else {
alert('No items selected.');
}
}
});
Thanks everybody!
I am sorry for my typos.I am working on proof of concept C# ASP.NET MVC application where I need to pass data between two views when there is no post and get. One view launches a modal dialog and I need communication between them. We are using JQuery.
I have a view called Charges.cshtml with a data grid. The first column of the datagrid may have span element or a link element depending on a
property which will tell whether the charge have single or multiple descriptions. The view looks like below.
If the charge has multiple descriptions user will click the corresponding description link( Description2 in this case ) and a modal dialog will open showing various descriptions like below
Now in this modal dialog user will confirm/select one description. Now I need to close the modal dialog and update the description of selected
charge like below
The hard part here is how to pass data between two views. I am ok to pass data via controller or via javascript.
I tried various ways to pass selected charge from Charges.cshtml to LoadLoanChargeDescriptions method in LoanCharge controller like json serialize, ViewData, ViewBag, TempData and so on but of no use. I can pass simple data types like int, string, float but not whole object. I feel I need to pass CurrentDescription and Descriptions to my controller and from their I need to move to other pieces. I tried to pass List of strings but could not see how to access them in controller since I got count as 0 in my controller. I am able to open popup of multiple descriptions UI ( for now just added Hello text )
Please see below for my code snippets
Charges.cshtml
#model ChargeViewModel
#using (Html.FAFBeginForm())
{
<div>
<table>
<tbody>
<tr >
//.....
<td>
#if(Model.IsMultipleMatch)
{
var loanCharge = Model as ChargeViewModel;
if (loanCharge.IsMultipleMatch == true)
{
//string vm = #Newtonsoft.Json.JsonConvert.SerializeObject(loanCharge);
<span>
<a
onclick="ShowMatchingDescriptions('#Url.Action("LoadLoanChargeDescriptions", "LoanCharge")','', '920','500')">
#loanCharge.Description
</a>
</span>
}
}
else
{
<span>Model.Description</span>
}
</td>
</tr>
</tbody>
</table>
</div>
}
public class ChargeViewModel
{
public string Description {get;set;}
public bool IsMultipleMatch {get;set;}
public List<string> Descriptions {get;set;}
}
public class LoanChargeController
{
public ActionResult LoadLoanChargeDescriptions()
{
// get data here and pass/work on
return View("_PartialMultipleMatchPopup", null);
}
}
In Review.js
function ShowMatchingDescriptions(popUpURL, windowProperties, w, h) {
try {
var left = (screen.width / 2) - (w / 2);
var top = (screen.height / 2) - (h / 2);
var properties = windowProperties + "dialogwidth:" + w + "px;dialogheight:" + h + "px;dialogtop:" + top + "px;dialogleft:" + left + "px;scroll:yes;resizable:no;center:yes;title:Matching Lender’s Fee;";
$.when(
window.showModalDialog(popUpURL, window, properties)
)
.then(function (result) {
var childWindow = result;
});
}
catch (err) {
alert("Error : " + err)
}
}
UPDATE 1
I updated my question and posted more details.
Thanks in advance.
UPDATE 2
Please see for my solution at below link.
MVC pass model between Parent and Child Window
Why don't you use the AJAX for pass the data?
function ChargeViewModel() {
this.Description ='';
this.IsMultipleMatch =false;
}
var chargeViewModel= new ChargeViewModel();
var data = JSON.stringify({ 'chargeViewModel': chargeViewModel });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '#Url.Action("LoadLoanChargeDescriptions", "LoanChargeController")',
data: data,
success: function (result) {
//result will be your partial page html output
},
failure: function (response) {
}
});
Then you have to change the controller like this:
public ActionResult LoadLoanChargeDescriptions(ChargeViewModel chargeViewModel)
{
// get data here and pass/work on
return View("_PartialMultipleMatchPopup", null);
}
Let me know you have queries..
I have a numerical "badge" value that I'm trying to display on a menu in my MVC 5.1 app.
<span id="myBadge" class="badge menu-badge">#SessionData.MyCount</span>
I have a SessionData class so I don't have to pass around magic strings.
public class SessionData
{
const string MyCountKey = "MyCount";
public static int MyCount
{
get { return HttpContext.Current.Session[MyCountKey] != null ? (int)HttpContext.Current.Session[MyCountKey] : 0; }
set { HttpContext.Current.Session[MyCountKey] = value; }
}
}
The badge is initially populated from a base controller which performs a database call.
SessionData.MyCount = CountThingsFromDatabase();
I use javascript & jquery on the front-end as users modify data. If the count reaches 0, a jquery command hides the "0" badge.
function setBadgeValue(badgeName, count) {
$(badgeName).html(count);
count > 0 ? $(badgeName).show() : $(badgeName).hide();
}
All of this works fine with one exception. When the controller retrieves a count of "0", I'd like to hide the badge from the view in the same manner as the jquery show/hide commands. The front-end jquery piece works wonderfully, but I'm unsure of how to accomplish the same effect from the controller side of things.
Any help would be greatly appreciated.
Update 1:
The views I have utilize Telerik/Kendo objects. This is from a view which displays a Kendo grid. Each grid row has a button that is tied to this method. I'm not sure it would help to post the entire view/controller since most of it is Kendo related.
function addToCart(e) {
// Get the grid data
var grid = $("#Grid").data("kendoGrid");
var dataItem = grid.dataItem(grid.select());
// Add item to the cart
$.ajax({
url: 'Search/AddCart',
data: { itemId: dataItem.ItemId },
success: function () {
$('_MyBadge').html();
$('_Layout').html();
// Update the count
setBadgeValue("#myBadge", 1);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert('Failed to add item #' + dataItem.itemId + ' to your cart.\nStatus: ' + textStatus + '\nError: ' + errorThrown);
}
});
}
How about doing this on the view?
#if (SessionData.MyCount == 0)
{
<span id="myBadge" class="badge menu-badge" style="display: none;">#SessionData.MyCount</span>
}
else
{
<span id="myBadge" class="badge menu-badge">#SessionData.MyCount</span>
}
No need to use the controller in any way, just hide your badge initially in the view if your count is zero.
<span id="myBadge" class="badge menu-badge" style="display: #(SessionData.MyCount > 0 ? "block" : "none");">#SessionData.MyCount</span>