Dynamically adding table rows with functions - javascript

I have a table that I need to dynamically add/remove rows from. Each row has a hyperlink in the final column to remove the record. Since you can dynamically add rows after the page loads, occasionally this record won't be found in the database.
When the user clicks on the "Delete" link, an ajax function is called to remove the record from the database. As long as the function server-side function does not crash, the operation will send back as a success.
Once the ajax function's success function is called, I would like to remove the tr from the table.
I can do this with each row that exists in the table once the page loads. The ajax function sends the proper info back to the server, and the tr is removed from the table. However for each tr I add after the delete ajax function will not fire, and the tr is left on the page.
View
<fieldset>
<legend>Agent Ids</legend>
<table id="agentTable">
<thead>
<tr>
<th>State Code</th>
<th>Company Code</th>
<th>Agent ID</th>
<th>Non-Res Biz NY</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.BankListAgentIds)
{
#Html.Partial("AgentIdPartial", item)
}
</tbody>
Add Another
</table>
</fieldset>
Parial View
#model CollectionItemTest.Models.BankListAgentId
#{
Layout = null;
}
#using (Html.BeginCollectionItem("BankListAgentIds"))
{
#Html.HiddenFor(model => model.TableId)
#Html.HiddenFor(model => model.BankID)
<tr>
<td>
#Html.EditorFor(model => model.StateCode)
</td>
<td>
#Html.EditorFor(model => model.CompanyCode)
</td>
<td>
#Html.EditorFor(model => model.NonResBizNY)
</td>
<td>
#Html.EditorFor(model => model.AgentId)
</td>
<td>
#Html.ActionLink("Delete", "", "", new { href = "javascript:void(0)", id = Model.TableId })
</td>
</tr>
}
jQuery
<script type="text/javascript">
$(function() {
$('#agentTable').on('click', 'tr a', function(e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
})
});
$(document).ready(function () {
$('.addCode').click(function() {
$.ajax({
url: '#Url.Action("BlankRow", "BankList")',
dataType: 'html',
cache: false,
success: function(html) {
$("#agentTable > tbody").append(html);
}
});
});
});
</script>
Controller Functions
public JsonResult DeleteRow(int id)
{
if (id == 0) return null;
var agent = (from a in db.BankListAgentIds
where a.TableId == id
select a).FirstOrDefault();
if (agent == null) return Json("Agent Id not found", JsonRequestBehavior.AllowGet);
db.BankListAgentIds.Remove(agent);
return null;
}
public ViewResult BlankRow()
{
return View("AgentIdPartial", new BankListAgentId());
}

Followed this post and used the .live command.
$('#agentTable').live('click', 'tr a', function (e) {
$.ajax({
url: '#Url.Action("DeleteRow", "BankList")',
data: { id: $(this).attr('id') },
dataType: 'html',
cache: false,
context: this,
success: function () {
$(this).parents('tr').remove();
}
});
});

Related

Passing Table data from view to controller not working

I am trying to send the data of my table with dynamic values to the controller.
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td class="AutoId">#item.AutoID <input type="hidden" name="AutoID" value="#item.AutoID" /></td>
<td class="hove" name="text"> <b>#item.Text</b><br /><label></label></td>
<td class="Active">#item.Active</td>
<td id="oBy" name="OrderBy">#item.OrderBy</td>
</tr>
}
}
above is the table structure
I am using below ajax call to send one field for example...
<script>
$(document).ready(function () {
alert("Test 1");
$("#btnSave").click(function (e) {
alert("Test 2");
$.ajax({
type: "POST",
url: '#Url.Action("LookupManagementUpdate", "Admin", new { Area = "Admin" })',
data: $(".hove").val(),
dataType: 'json',
async: false,
success: function (response) {
Success = true;
},
error: function (response) {
},
});
});
});
</script>
Below is my controller code
public string LookupManagementUpdate(string text)
{
return "answer"+Request["text"]+text;
}
I tried using both Request and parameter method to fetch the data but it does not display the table data.
This is a c# mvc ado.net based project
try using Ajax.BeginForm and ajaxOptions Onsuccess

Autocomplete for textbox Control under HTML table

I have a Html table(instead of Grid control I used HTML table) having multiple rows with one drop down and one textbox control.I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
And Jquery code which I tried is as follows.
$(function () {
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
});
You're saying
having multiple rows with one drop down and one textbox control. I want auto complete function for that text box
and I'm also seeing
$('#Item_Item_Name').autocomplete(...
Are you giving the same id to every textbox? If so, that will not work. Ids have to be unique. Jquery will assume you have only 1 and fire/listen to events only for that 1 textbox.
Consider rewriting your JS using classes for the textbox instead.

under HTML table Autocomplete for HtmlEditor Control

I have a Html table having multiple rows with one drop down and one textbox control.
I want auto complete function for that text box.I implemented the following code for auto complete but it is firing for only first row.The rows are added Dynamically (in jquery) its not workig for those rows.
CODE:
<table class="table table-bordered table-hover datatable-highlight" id="tWDE_Items">
<thead>
<tr>
<th style="display:none">ItemId</th>
<th>Item Name</th>
<th>UOM</th>
</tr>
</thead>
<tbody>
#foreach (var Item in Model.Data_Wde_ItemGrid)
{
<tr class="datarow">
<td style="display:none">#Item.Item_Id</td>
<td>#Html.EditorFor(m => Item.Item_Name, new { htmlAttributes = new { #class = "form-control" } }) </td>
<td>#Html.DropDownListFor(m => Item.UOM_Id, new SelectList(Item.UOMDetails, "UomId", "UomName"), htmlAttributes: new { #class = "form-control", id = "UomId" })</td>
</tr>
}
</tbody>
</table>
Java Script :
$('#Item_Item_Name').autocomplete({
source: function (request, response) {
debugger;
var param = { ItemName: $('#Item_Item_Name').val() };
$.ajax({
url: "/WDE/GetAutoCompleteItemList",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
val: item.split('÷')[0],
label: item.split('÷')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
change: function (e, i) {
if (i.item) {
}
else {
$('#Item_Item_Name').val('');
$('#Item_Item_Id').val('');
}
},
select: function (e, i) {
debugger;
$('#Item_Item_Name').val(i.item.label);
$(this).closest("tr").find("td").eq(2).html(i.item.val);
},
minLength: 1
});
Your autocomplete() call works only on the elements that are in the dom the time you call it. So for dynamically added elements you'll need the call the function again (after the new row was added).
One more thing to notice is that any call using the element id ($('#Item_Item_Name')) will work only for the first element with that id, because ids are meant to be unique. So you'll need to change the selector to get the input from the new row.
Create a function that inits the autocomplete And after every row you add, call that function on the element you want.
function initAutoComplete(elem) {
$(elem).autocomplete({ /* the same as you use now */ });
}
// after you addded the new row
initAutoComplete($(newRow).find('.autocopmlete-input'));

I do not know why this Java Script code not run in MVC

In dropdownlist onchange event call FillSystem() Ajax Request is sent but scopeId selector do not run this below method.
function FillSystem() {
var _scopeId = $('#ScopeId').val();
var _roleId = $('#Role_Id').val();
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId").html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId").append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
<table class="table w3-striped w3-border w3-card-4" style="width: 65%">
<tr>
<td>
Scope
</td>
<td>
#Html.DropDownList("ScopeId", null,"--Please Select--", new { style = "width:250px", #onchange = "FillSystem()" })
</td>
</tr>
<tr>
<td>System</td>
<td>
#Html.DropDownList("SystemId", null, "--please select--", new { style = "width:250px" })
</td>
</tr>
</table>
you use DropDown in table and probably multiple row exist, and multiple id with same, your $('#ScopeId') selector, select first element with ScopeId.
first remove #onchange = "FillSystem()" from DropDownList, then try this code
(function ($) {
function FillSystem() {
var _scopeId = $(this).val();
var _roleId = $('#Role_Id').val();
var $row = $(this).closest("tr");
$.ajax({
url: '/Account/FillSystem',
type: "GET",
dataType: "JSON",
data: { scopeId: _scopeId, roleId: _roleId },
success: function (systems) {
$("#SystemId", $row).html(""); // clear before appending new list
$.each(systems, function (i, system) {
$("#SystemId", $row).append(
$('<option></option>').val(system.System_Id).html(system.SystemName));
});
}
});
}
$(function () {
$("table").on("change", "#ScopeId", FillSystem)
});
}(jQuery));

model not passing to controller from view

I am new to mvc and javascript.At first I am using javascript to appned the parital view in divsion
$('.btngo').click(function (e) {
var fid = $('#FiscalYear_FYId').val();
alert($('#FiscalYear_FYId').val());
$.ajax({
type: 'Get',
url: '#Url.Action("RateList", "Rate")',
data: { fyid: fid },
success: function (sc) {
$('#Ratelist').html(sc);
}
});
});
The partial view is of model FHIControl.Model.StationeryRate.RateDTO which consists a submit button my view looks like
#using (Html.BeginForm("Ratelist", "Rate", FormMethod.Post))
{
#Html.ValidationSummary(true)
<table>
<thead>
<tr>
<th>Item Id</th>
<th>Item Name</th>
<th>Rate</th>
</tr>
</thead>
#Html.HiddenFor(x=>Model.FiscalYear.FYId)
#foreach (var item in Model.RateList)
{
<tr>
#Html.HiddenFor(x => item.ItemId)
<td>#{count++;}#count</td>
<td>#Html.DisplayFor(x => item.ItemName)</td>
<td>#Html.TextBoxFor(x => item.Rate)</td>
</tr>
}
</table>
<p>
<input type="submit" value="Ok" id="btnsubmit" />
</p>
}
The button submit is submiting the form but there is no model items.Why is it so?Is there any way to make this work?
There is no model items because you are only passing the value of FiscalYear_FYId:
var fid = $('#FiscalYear_FYId').val();
$.ajax({
data: { fyid: fid },
});
which should be:
$.ajax({
data: $form.serialize(),
});
where $form is a reference to your form. That you can either give a name for faster and better reference, or you can reference it like this:
var $form = $("#btnsubmit").parents('form');

Categories