I have a function and get the response from the controller.after that I need to append the details to the table.All I have done.But i can see the result only after I click the table .I think my datatable is not reloaded.How Can I solve this problem.My code is below.and html code is added here.When the select box changes according to the result the table is updated
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
$('#tblClassName tbody').empty();
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
$('#tblClassName').append(trHtml);
$('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
},
error: function (data) {
}
});
return false;
});
<div class="box-body">
<form id="MenuPermission">
<div class="form-group">
<select class="form-control MemberSelect" name="MemberType"></select>
</div>
<div id="example1_wrapper" class="dataTables_wrapper form-inline dt-bootstrap">
<table class="table table-bordered table-striped" id="tblClassName">
<thead>
<tr>
<th>Sl.NO
</th>
<th>Parent Menu
</th>
<th>Menu
</th>
<th>Is Allowed
</th>
<th>Function</th>
</tr>
</thead>
<tbody>
#{
int i = 1;
foreach (var item in Model)
{
<tr>
<td>#i
</td>
<td>
#Html.DisplayFor(modelItem => item.LibrarySchooberryMenuDetails.MenuName)
</td>
<td>
#Html.DisplayFor(modelItem => item.MenuName)
</td>
<td>
<input type="checkbox" class="MenuMap" id="#item.MenuID" data-id="#item.MenuID"/>
</td>
<td>
<table>
#foreach (var function in item.LibrarySchooberryMenuFunctions)
{
<tr>
<td>
<input type="checkbox" class="FunctionMap" id="#function.MenuFunctionID" data-id="#function.MenuFunctionID"/>
#function.Name
<input type="hidden" value="#function.MenuID" class="menuID" />
</td>
</tr>
}
</table>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</form>
</div>
Refer to my answer here;
How to append ajax result in modal with datatable
First store the initialization to a variable, be sure to put this on the top of the script or inside a $(document).ready(function(){});
var dataTable = $('#tblClassName').DataTable({});
Instead of using jquery append to the table, you have to use the .add() function from the datatable object, then .draw() for refresh;
dataTable.row.Add().draw();
UPDATE:
dataTable.row.add($(trHtml)).draw();
To clear the datatable, use .clear() .
dataTable.clear();
Use this script;
$(document).ready(function(){
var dataTable = $('#tblClassName').DataTable({
'paging': true,
'lengthChange': false,
'searching': true,
'ordering': true,
'info': true,
'autoWidth': false
});
});
$(document).on('change', '.MemberSelect', function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ memberTypeID: $(".MemberSelect").val() }),
url: "#Url.Action("GetUserMenuDetails", "MenuPermission")",
success: function (data) {
var trHtml = '';
// revised //////////////////////
dataTable.clear();
/////////////////////////////////
$.each(data, function (i, item) {
trHtml = trHtml + '<tr><td></td><td>' + (item.LibrarySchooberryMenuDetails!=null? item.LibrarySchooberryMenuDetails.MenuName : "") + '</td>'
'<td>' + item.MenuName + '</td>'
'<td><input type="checkbox" class="MenuMap" id="' + item.MenuID + '" data-id="' + item.MenuID + '"/></td>'
'<td><table>';
$.each(data.LibrarySchooberryMenuFunctions, function (j, functions) {
trHtml = trHtml + '<tr><td><input type="checkbox" class="FunctionMap" id="' + functions.MenuFunctionID + '" data-id="' + functions.MenuFunctionID + '"/>'
+ functions.Name + '<input type="hidden" value="' + functions.MenuID + '" class="menuID" /></td></tr>'
});
trHtml = trHtml + '</table></td></tr>'
});
// revised //////////////////////
dataTable.row.add($(trHtml)).draw();
/////////////////////////////////
},
error: function (data) {
}
});
return false;
});
Related
Im trying serialize form and binding into model, but some how child of model InsertToUsertbls returns NULL. Can any help me please :)
I have the following model:
public class MangeAddUsers
{
public List<InsertToUsertbl> InsertToUsertbls { get; set; }
public class InsertToUsertbl
{
public InsertToUsertbl()
{
}
public int PX2ID { get; set; }
public string CustomerNR { get; set; }
public string SellerPersonCode { get; set; }
public string NameOfCompany { get; set; }
public string CompanyNo { get; set; }
}
}
JavaScript to Get data and than load them into form:
<script>
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function myfunction() {
$.ajax({
type: "GET",
url: "/Account/GetCustomerContactInfo",
data: {ids: '10883'},
dataType: 'json',
traditional: true,
success: function (values) {
var holderHTML = "";
for (var i = 0; i < values.length; i++) {
value = values[i]
if (value != null) {
var guid = uuidv4();
holderHTML += '<tr id="row' + value.CustomerNo + '">';
holderHTML += '<input type="hidden" name="InsertToUsertbls.Index" value="' + guid + '" />';
holderHTML += '<td><input class="inpt-tbl" type="hidden" id="CustomerNR" name="InsertToUsertbls[' + guid + '].CustomerNR" value="' + value.CustomerNo + '" /></td>';
holderHTML += '<td><input class="inpt-tbl" type="hidden" id="NameOfCompany" name="InsertToUsertbls[' + guid + '].NameOfCompany" value="' + value.NameOfCompany + '" /></td>';
holderHTML += '<td><input type="hidden" id="CompanyNo" name="InsertToUsertbls[' + guid + '].CompanyNo" value="' + value.CompanyNo + '" /></td>';
holderHTML += '<input type="hidden" id="SellerPersonCode" name="InsertToUsertbls[' + guid + '].SellerPersonCode" value="' + value.SalgePersonCode + '" />';
holderHTML += '</tr>';
}
}
$('#output').append(holderHTML);
},
error: function () {
console.log('something went wrong - debug it!');
}
})
};
</script>
And when data load into form:
<form id="mangeUserFrom">
<div id="output">
<tr id="row10883">
<input type="hidden" name="InsertToUsertbls.Index" value="fd3424ab-160d-4378-af65-ad2b790812ec">
<td>
<input class="inpt-tbl" type="hidden" id="CustomerNR" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CustomerNR" value="10883">
</td>
<td>
<input class="inpt-tbl" type="hidden" id="NameOfCompany" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].NameOfCompany" value="Some Name">
</td>
<td>
<input type="hidden" id="CompanyNo" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CompanyNo" value="849">
</td>
<input type="hidden" id="SellerPersonCode" name="InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].SellerPersonCode" value="TT">
</tr>
</div>
</form>
<button type="button" id="createuser" onclick="PostForm();">POST</button>
JavaScript for serializing:
<script>
function PostForm() {
var formdata = $("#mangeUserFrom").serializeArray();
console.log(formdata);
$.ajax({
"url": '#Url.Action("MangeCreateUsers", "Account")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
This is the result of the serialization:
{name: "InsertToUsertbls.Index", value: "fd3424ab-160d-4378-af65-ad2b790812ec"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CustomerNR", value: "10883"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].NameOfCompany", value: "Some Name"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].CompanyNo", value: "849"}
{name: "InsertToUsertbls[fd3424ab-160d-4378-af65-ad2b790812ec].SellerPersonCode", value: "TT"}
This is my controller method I'm trying to POST to:
[HttpPost]
public JsonResult CreateCustomers(CreateCustomers model)
{
return Json(model, JsonRequestBehavior.AllowGet);
}
Screenshots:
The below code generates 5 drop-down-lists.
#{
for (int i = 0; i < 5; i++) { <tr>
<td> #Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { #class = "form-control ", #type = "text",
#placeholder = " QNo", #required = "", #id = "txtQNo", #style = "width:60px;" } }) </td>
<td> </td>
<td> #Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty, "Value", "Text"), "Select Question",
new { #class = "form-control ", #id = "Question", #style = "width:900px;" })</td>
</tr>
}
}
I am trying to populate the above 5 drop-down menu with a bunch of values I receive through my below ajax call
$("#ReflectionType").on("change", function (event) {
$.ajax({
type: "post",
url: "/Question/GetQuestions",
data: { TypeId: $('#ReflectionType').val() },
datatype: "json",
traditional: true,
success: function (data) {
debugger;
$.each(data, function (index, value) {
var markup = '';
$("#Question").append('<option value="' + value.Question + '">' + value.Question + '</option>');
});
}
});
The above snippet only updates one of the drop-down list(the first drop-down menu) where it should be updating all five drop-down list.
#{
for (int i = 0; i < 5; i++) { <tr>
<td> #Html.Editor("[" + i + "].QNo", new { htmlAttributes = new { #class = "form-control ", #type = "text",
#placeholder = " QNo", #required = "", #id = "txtQNo", #style = "width:60px;" } })</td>
<td> </td>
<td> #Html.DropDownList("[" + i + "].Question", new SelectList(string.Empty,"Value", "Text"), "Select Question",
new { #class = "form-control ", #id = "Question"+i, #style = "width:900px;" })</td>
</tr>
}
}
This will generate unique id as follows Question0, Question1, Question2, Question3, Question4
$("#ReflectionType").on("change", function (event) {
$.ajax({
type: "post",
url: "/Question/GetQuestions",
data: { TypeId: $('#ReflectionType').val() },
datatype: "json",
traditional: true,
success: function (data) {
debugger;
$.each(data, function (index, value) {
var markup = '';
for(let j = 0; j < 5; j++){
$("#Question"+j).append('<option value="' + value.Question + '">' + value.Question + '</option>');
}
});
}
});
As I can see your loop is running through 5 iteration you can run it in the same way and append the data from ajax call. Or you can use starts with selector as follows
$('[id^=Question]').each(function(index,element){
$(element).append('<option value="' + value.Question + '">' + value.Question + '</option>');
})
Hopefully this will solve your problem. Happy Coding!
I'm trying to call $.ajax method to retrieve NORTHWND Employees details based on the search criteria. But, for some reason, country, and title variable are always returning null. I am not understanding where I am doing wrong.
Below is the clear explanation.
Below is the code in AjaxDemoRequestPage.aspx
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country = $("#txtCountry").val();
data.title = $("#txtTitle").val();
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
Below is the code in PostTarget.aspx.cs page. In this page, when debugging I am always getting country, and title as null.
public partial class PostTarget : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var country = Request.Form["country"];
var title = Request.Form["title"];
var db = new NORTHWNDEntities();
var emps = db.Employees
.Where(x => x.Country.Contains(country) || x.Title.Contains(title))
.Select(x => new EmployeeSearchResult
{
EmployeeID = x.EmployeeID,
FirstName = x.FirstName,
LastName = x.LastName
});
Response.Clear();
Response.Write(JsonConvert.SerializeObject(emps));
Response.Flush();
Response.End();
}
}
Can anyone please suggest me where I am doing wrong?
The contentType should be this:
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
My blunder mistake was that I never made call to $.ajax method. Below is the modified and working code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
$.ajax(data);
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
ID generated by ASP.NET will not same as you have given. this is the reason you are getting null value .
You can access ASP.NET control in javascript in this way.
document.getElementById('<%= txtCountry.ClientID %>').value
And also you can simple use html button instead of ASP.NET button for making ajax request.
Here is your updated code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
I have a Select2 list and added multiple items to the table.But i wanted to check if items already exists in the table or not first and IF not only then add new item But below my code doesn't work.
In this code everytime it shows Not Found & add duplicate rows
HTML Part
<select id="select-product" multiple style="width: 300px">
</select>
Code
$("#select-product").change(function () {
debugger;
var $option = $('#select-product option');
if ($("#select-product option[value='ProductCode']").length > 0) {
alert("Found");
}
else
{
alert("Not Found");
}
$option.each(function () {
if ($(this).is(':selected')) {
debugger;
var itm = $(this).is(':selected');
var temp = $(this).attr('ProductCode');
var row = '<tr>';
row += '<td class="itmcode">' + $(this).attr('ProductCode') + '</td>';
row += '<td class="itmname">' + $(this).text().replace(temp, " ") + '</td>';
row += '<td class="unit">' + $(this).attr('Unit_UnitId') + '</td>';
row += '<td class="retprice" dir="rtl" align="right">' + $(this).attr('RetailPrice') + '</td>';
row += '<td class="col-md-1 inpqty" dir="rtl">' + '<input type="text" class="input-qty form-control col-md-3 center-block input-sm" data-id="' + $(this).val() + '" data-prod-id="' + $(this).attr('Value') + '">' + '</td>';
row += '<td class="col-md-1 disc" dir="rtl">' + '<input type="text" class="input-disc form-control input-sm">' + '</td>';
row += '<td class="tot" dir="rtl" align="right">0</td>';
row += '<td class="imgdel"><img class="btn-img-del" src="../Images/delete.png" alt="" title="Delete" /></td>';
row += '</tr>';
table.append(row);
}
});
$('#select-product').select2('data', null);
});
Multiple Products Code
function CallMultipleProducts() {
$.ajax({
type: "POST",
url: '/Sales/GetMultipleProducts',
contentType: "application/; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
debugger;
if (msg._productlist.length > 0) {
debugger;
$.each(msg._productlist, function (index, item) {
debugger;
$('#select-product').append($("<option></option>")
.attr("Value", item.ProductId)
.attr("RetailPrice", item.RetailPrice)
.attr("ProductCode", item.ProductCode)
.text((item.ProductCode) + " " + (item.ProductName))
);
});
}
}
// error: AjaxError
})
}
Make sure that you have only select item with unique id="select-product" throughout your html.
Try below code, use .find()
if ($("#select-product").find("option[value='ProductCode']").length > 0) {
alert("Found");
}
Please try adding the below option to your select2 options if the element is input type="text",
$("#select-product").select2({
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} }
});
If you are using <select> element, I'm afraid you can't use this option. You have to use input instead. You might find something useful here.
I got an issue with my Ajax. When I clicked on the Remove From Cart, The ajax seems not rendering anything. Any hint? Here is my code:
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Panier", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
Remove From Cart
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
ShoppingCart.cs
public int RemoveFromCart(int id)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.ProduitId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantite > 1)
{
cartItem.Quantite--;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
Here is the Chrome output PF12 for the network tab
Change:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
To:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
Another option, although not recommended is to remove the [HttpPost] from the top of your controller. This will raise other issues for you, as the recommended way to send data using ajax is 'POST'