How can I select all checkboxes in mvc - javascript

This code below select only one by one checkbox, how can I transform this code so I can select all checkboxes by one click, but I need my variables to stay defined.
$('.checktip').click(function () {
var iduser = $('.iduser').val();
var idtip = $(this).attr('idtip');
var che = $(this).prop('checked');
$.ajax({
url: UrlSettingsDocument.OrgUnits,
data: { iduser: iduser, idtip: idtip, che: che },
type: "POST",
success: function (result) {
if (result.result == "Redirect") {
window.location = result.url;
}
}
});
});
I using this variables for controller where I save this values in database when I check them or unchecked.
Here is my html code
<input type="hidden" value="#ViewBag.iduser" id="iduser" />
<hr />
<table class="table table-striped grid-table">
<tr>
<th>Samp</th>
<th>Id of Book</th>
<th>
//Checkbox for check all *(NOT IMPLEMENTED)*
<input type="checkbox" id="box" name="checkAll" />
</th>
</tr>
#foreach (var item in (IEnumerable<cit.Models.getCheIdTip_Result>)Model)
{
<tr>
<td>#item.idtip</td>
<td>#item.tipname</td>
<td>
#*#Html.CheckBox(item.id.ToString(), item.iduser == ViewBag.iduser ? true : false, new { idtip = item.idtip, #class = "checktip" })*#
<div class="pure-checkbox">
<input type="checkbox" idtip="#item.idtip" class="checktip" checked="#(item.iduser == ViewBag.iduser ? true : false)" name="#item.id.ToString()" id="#item.id.ToString()" />
<label for="#item.id.ToString()"></label>
</div>
</td>
</tr>
}
</table>

Following code should work with your code
$('#box').click(function(){ $('.checktip').prop('checked', true); }};

Related

Send data to controller via Javascript

I have a html table in with razor and I want to send some data from the table to a controller via Javascript.
I tried several different solutions but the data never seems to reach my controller while alerts are being hit. The breakpoints in the controller are never being hit which indicates to me that the data can't reach the controller.
I want the value of #item.PartId and the value of checked to be send to the controller.
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
Javascript
<script type="text/javascript">
$(function ClickHandle() {
$("input[name='IsChecked']").change(function (element) {
var table = document.getElementById("table1");
for (var i = 1; i < table.rows.length; i++) {
var row = table.rows[i];
var lastorder = row.cells[12].firstChild;
var check = lastorder.checked;
if (check) {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = "yellow";
}
else {
var x = document.getElementById("table1").getElementsByTagName("tr");
x[i].style.backgroundColor = null;
}
//post item.partid and value of check to controller here.
}
});
});
</script>
Controller
[HttpPost]
public ActionResult PostIsChecked(string partId, string isChecked)
{
Part part = new Part
{
id = partId,
isChecked = isChecked
};
//Do stuff
receipt.UpdateCheckedStatus(part);
}
You can try to put a hidden input into <tr></tr>,and set its value with #item.PartId.Then use ajax to post data to action.Here is a demo:
<div class="Table">
{
<table id="table1" class="table table-striped TableData">
#{var id = 0;}
#foreach (var item in Model.PieceViewItems)
{
id++;
<tr id="#id">
<td>#id</td>
<td><label>#item.PartDescription</label> <br /><input hidden value=#item.PartId/> #item.PartId (#item.StatusCode)</td>
<td>#item.Supplier</td>
<td style="width: 100px !important">
#item.TijdOpO3 #if (item.TijdOpO3 == "1")
{<text>dag</text>}
else
{ <text>dagen</text>}
</td>
<td>#item.KeurCode</td>
<td>#item.PromiseDate</td>
<td>#item.WidthAndPartType</td>
<td>
#item.PieceLengthWithUnit <br /> #item.NrOfPieces #if (item.NrOfPieces == 1)
{<text>rol</text> }
else
{ <text>rollen</text>}
</td>
<td>
#if (item.NumberReceived == "0")
{<text>NIEUW</text> }
else
{ #item.NumberReceived}
</td>
<td>#item.VoorraadQty m</td>
<td style="width: 100px !important">
#item.SalesOrderQty m <br /> #item.NrOfSalesOrders #if (item.NrOfSalesOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td style="width: 100px !important">
#item.StalenOrdersQty m <br /> #item.NrOfStalenOrders #if (item.NrOfStalenOrders == 1)
{<text>order</text>}
else
{<text>orders</text>}
</td>
<td><input type="checkbox" name="IsChecked" onclick="ClickHandle(this)" style="width:30px;height:30px;margin-left:20px;margin-top:20px"> </td>
</tr>
}
</table>
</div>
js:
$("input[name='IsChecked']").change(function () {
var checked = this.checked;
var PartId = $(this).parent().parent().find("input")[0].value;
$.ajax({
type: "POST",
url: "PostIsChecked",
data: { "isChecked": checked, "partId": PartId},
success: function (data) {
}
});
});

Update datatable using Knockout JS

I've a HTML datatable I'm filling data to datatable using knockout js using 'foreach'. Here is my code.
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12 /css/jquery.dataTables.min.css" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div id="dvMain">
<table style="width: 300%">
<tr>
<td>
<table id="tblmain">
<tr id="trCategory" data-bind="visible: flagCategory">
<td>
<table>
<tr id="InsertUpdateCategory" data-bind="visible: flagInsertCategory">
<td>
<table>
<tr>
<td>Category Name : </td>
<td>
<input type="text" id="txtCategoryName" maxlength="100" data-bind="value: txtCategoryName" />
</td>
</tr>
<tr>
<td>Is Active : </td>
<td>
<input type="checkbox" id="chkIsActiveCategory" data-bind="checked: chkCategoryActive" />
</td>
</tr>
<tr>
<td></td>
<td>
<button id="btnSaveCategory" data-bind="click: SaveCategory">Save</button>
<input type="hidden" id="hdnCategoryId" />
<button id="btnCancelCategory" data-bind="click: CancelCategory">Cancel</button>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table style="width: 300%" id="tblCategory">
<thead>
<tr>
<th style="width: 100%">Category Name</th>
<th style="width: 100%">Is Active</th>
<th style="width: 100%">Edit</th>
<th style="visibility: hidden">CategoryId</th>
<th style="visibility: hidden">MgaCode</th>
</tr>
</thead>
<tbody data-bind="foreach: CategoryCollection()">
<tr>
<td data-bind="text: CategoryName"></td>
<td data-bind="text: IsActive"></td>
<td><a id="hrefEditCategory" data-bind="click: function () { ViewModel.EditCategory($data); }">Edit</a></td>
<td data-bind="text: MGACategoryId" style="display: none"></td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</body>
<script type="text/javascript">
var SelectedCategory = 0;
var CategoryId = 0;
var row = {
CategoryName: "",
IsActive: false,
MGACategoryId: null,
MGACode: null
};
$(document).ready(function () {
ViewModel = {
CategoryCollection: ko.observableArray(),
flagCategory: ko.observable(true),
flagInsertCategory: ko.observable(false),
EditCategory: ko.observable(),
txtCategoryName: ko.observable(''),
chkCategoryActive: ko.observable(false),
CategoryLink: function () {
this.flagCategory(true);
this.flagApplicationForm(false);
this.flagSubCategory(false);
},
CancelCategory: function () {
this.flagInsertCategory(false);
this.txtCategoryName('');
this.chkCategoryActive(false);
$('#btnSaveCategory').text('Save');
},
EditCategory: function (data) {
debugger;
this.flagInsertCategory(true);
this.txtCategoryName(data.CategoryName);
this.chkCategoryActive(data.IsActive);
CategoryId = data.MGACategoryId;
$('#btnSaveCategory').text('Update');
row = data;
},
SaveCategory: function () {
debugger;
var id = CategoryId;
var name = this.txtCategoryName();
var isactive = this.chkCategoryActive();
if ($('#btnSaveCategory').text() == 'Update') {
row.CategoryName = name;
row.IsActive = isactive;
this.CategoryCollection()
for (var i = 0; i < this.CategoryCollection().length; i++) {
if (this.CategoryCollection()[i].MGACategoryId == row.MGACategoryId) {
this.CategoryCollection()[i].CategoryName=name;
this.CategoryCollection()[i].IsActive=isactive;
}
}
}
else {
row.CategoryName = this.txtCategoryName();
row.IsActive = this.chkCategoryActive();
this.CategoryCollection.push(row);
this.flagInsertCategory(false);
}
},
}
debugger;
$.ajax({
type: "GET",
url: 'Datepicker/GetCategory',
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
debugger;
if (response != null) {
for (var i = 0; i < response.length; i++) {
ViewModel.CategoryCollection().push(response[i]);
}
}
},
error: function (data) {
debugger;
}
});
debugger;
ko.applyBindings(ViewModel);
});
</script>
</html>
I want to update my table using edit link given in table 'tblCategory'. Observable array for tblCategory is CategoryCollection(). Data is binded using JSON data from database. When I clicked on Edit button 'trInsertUpdateCategory' will be shown with filled row data. When I update data in textbox or checkbox and click on update button data is not updated in table. But when I add new data using that textbox and check box data is inserting and showing in table also. But update is not working for me please guide.
Dont know if this is what you are looking for, but there is a problem in your ajax success function.
success: function (response) {
debugger;
if (response != null) {
for (var i = 0; i < response.length; i++) {
ViewModel.CategoryCollection().push(response[i]);
}
}
}
Try changing it to
success: function (response) {
debugger;
if (response != null) {
for (var i = 0; i < response.length; i++) {
ViewModel.CategoryCollection().push(response[i]);
}
ViewModel.CategoryCollection.valueHasMutated();
}
}
Since right now, your observable array wont notify subscribers that its value is changed

Reading file contents and POSTing in combination with KO mechanism

I used this tutorial http://www.dotnetcurry.com/aspnet/1006/edit-html-table-crud-knockoutjs-aspnet-webapi to create an editable table with KnockOutJS, without adding the ASP.NET stuff (only the KO part, server-side API is implemented in PHP).
The tutorial works but I added a new feature which doesn't. Instead of outputting a text field I modified the instructions of the author to add a button instead of it in the table. What I am trying to achieve is to read the contents of a file image, store it in a variable and append in POST payload so as to be stored in a blob field in a database table.
Can someone please suggest an alternative way to achieve this or guide me to correct the existing one ? I'm quite a newbie to KnockOutJS and furthermore in Javascript.
var self = this;
//S1:Boolean to check wheather the operation is for Edit and New Record
var IsNewRecord = false;
// filename to be converted into string for uploading
var ImgFile = "";
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
//console.log("In handleFileSelect");
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
ImgFile = readerEvt.target.result;
//console.log("Printing the base64 ...");
//console.log(readerEvt.target.result);
};
reader.readAsBinaryString(file);
}
};
function executeCreateListener() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
//console.log("In if");
document.getElementById('filePicker').addEventListener('change', handleFileSelect, false); // this sh** resolves to null due to KO dynamic nature
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
self.ProductsApallou = ko.observableArray([]);
loadProducts();
//S2:Method to Load all Products by making call to WEB API GET method
function loadProducts() {
alert("Loading Data");
$.ajax({
type: "GET",
url: "http://127.0.0.1/goandwin/store_products.json?retrieve:Store_of_Product=1+Store_Product_id=999+Name=999+Subname=999+Imgname=999+Price=999+Product_Discount=999+Slogan=999+Origin=999+Description=999+Product_Code=999+Category_level_1_id=999+Product_Photo=999",
dataType: "json",
}).done(function(data) {
self.ProductsApallou(data);
}).fail(function(err) {});
alert("Success");
};
//S3:The Product Object
function Product(soproduct, spid, pname, subname, imgname, price, product_disc, slogan, origin, descript, product_code, cbid, pphoto) {
return {
Store_of_Product: ko.observable(soproduct),
Store_Product_id: ko.observable(spid),
Name: ko.observable(pname),
Subname: ko.observable(subname),
Imgname: ko.observable(imgname),
Price: ko.observable(price),
Product_Discount: ko.observable(product_disc),
Slogan: ko.observable(slogan),
Origin: ko.observable(origin),
Description: ko.observable(descript),
Product_Code: ko.observable(product_code),
Category_level_1_id: ko.observable(cbid),
Product_Photo: ko.observable(pphoto)
}
};
//S4:The ViewModel where the Templates are initialized
var ProdViewModel = {
readonlyTemplate: ko.observable("readonlyTemplate"),
editTemplate: ko.observable()
};
//S5:Method to decide the Current Template (readonlyTemplate or editTemplate)
ProdViewModel.currentTemplate = function(tmpl) {
return tmpl === this.editTemplate() ? 'editTemplate' : this.readonlyTemplate();
}.bind(ProdViewModel);
//S6:Method to create a new Blank entry When the Add New Record button is clicked
ProdViewModel.addnewRecordApallou = function() {
self.ProductsApallou.push(new Product(1, "auto", "default", "default", "default", 0, 0, "default", "default", "default", "default", 1, "default"));
IsNewRecord = true;
};
//S7:Method to Save the Record (This is used for Edit and Add New Record)
ProdViewModel.saveProduct = function(d) {
var Prod = {};
//console.log(d);
Prod.Store_of_Product = d.Store_of_Product;
Prod.Store_Product_id = d.Store_Product_id;
Prod.Name = d.Name ? d.Name : null;
Prod.Subname = d.Subname ? d.Subname : null;
Prod.Imgname = d.Imgname ? d.Imgname : null;
Prod.Price = d.Price ? d.Price : 0.0;
Prod.Product_Discount = d.Product_Discount ? d.Product_Discount : 0;
Prod.Slogan = d.Slogan ? d.Slogan : null;
Prod.Origin = d.Origin ? d.Origin : null;
Prod.Description = d.Description ? d.Description : null;
Prod.Product_Code = d.Product_Code ? d.Product_Code : null;
Prod.Category_level_1_id = d.Category_level_1_id ? d.Category_level_1_id : 1;
//console.log("Printing imgfile ...");
//console.log(ImgFile);
// <---- HERE what I am trying to achieve, if possible
if (ImgFile) {
Prod.Product_Photo = ImgFile; //take the string produced after uploaded
} else {
Prod.Product_Photo = d.Product_Photo; //take the string as it was
}
// ---->
//Edit the Record
if (IsNewRecord === false) {
$.ajax({
type: "PUT",
url: "http://127.0.0.1/goandwin/store_products/" + Prod.Store_Product_id,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: Prod
}).done(function(data) {
alert("Record Updated Successfully " + data.status);
ProdViewModel.reset();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
//The New Record
if (IsNewRecord === true) {
var tmp = Prod;
delete tmp.Store_Product_id; //remove the PK which is auto
IsNewRecord = false;
$.ajax({
type: "POST",
url: "http://127.0.0.1/goandwin/store_products",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: tmp
}).done(function(data) {
alert("Record Added Successfully " + data.status);
ProdViewModel.reset();
loadProducts();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
}
//S8:Method to Delete the Record
ProdViewModel.deleteProduct = function(d) {
$.ajax({
type: "DELETE",
url: "http://127.0.0.1/goandwin/store_products/" + d.Store_Product_id
}).done(function(data) {
//console.log(d.Store_Product_id);
alert("Record Deleted Successfully " + data.status);
ProdViewModel.reset();
loadProducts();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
//S9:Method to Reset the template
ProdViewModel.reset = function(t) {
this.editTemplate("readonlyTemplate");
};
ko.applyBindings(ProdViewModel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="tab-content">
<div id="Apallou" class="tab-pane fade in inactive">
<table class="table table-striped table-bordered table-hover" id="dataTables-exampleApallou">
<thead>
<tr>
<th>Store_of_Product</th>
<th>Store_Product_id</th>
<th>Name</th>
<th>Subname</th>
<th>Imgname</th>
<th>Price</th>
<th>Product_Discount</th>
<th>Slogan</th>
<th>Origin</th>
<th>Description</th>
<th>Product_Code</th>
<th>Category_level_1_id</th>
<th>Product_Photo</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody data-bind="template: { name: currentTemplate, foreach: ProductsApallou }"></tbody>
</table><br><input type="button" value="Add New Record" data-bind="click: function () { ProdViewModel.addnewRecordApallou(); }" /><br></div>
</div>
</div>
</div>
</div>
</div>
<!-- /#wrapper -->
<script type="text/html" id="readonlyTemplate">
<tr>
<td><span data-bind="text: Store_of_Product"></span></td>
<td><span data-bind="text: Store_Product_id"></span></td>
<td><span data-bind="text: Name"></span></td>
<td><span data-bind="text: Subname"></span></td>
<td><span data-bind="text: Imgname"></span></td>
<td><span data-bind="text: Price"></span></td>
<td><span data-bind="text: Product_Discount"></span></td>
<td><span data-bind="text: Slogan"></span></td>
<td><span data-bind="text: Origin"></span></td>
<td><span data-bind="text: Description"></span></td>
<td><span data-bind="text: Product_Code"></span></td>
<td><span data-bind="text: Category_level_1_id"></span></td>
<td><img width="60px" height="70px" data-bind="attr:{src: Product_Photo}" /></td>
<td>
<input type='button' value='Edit' data-bind='click: function () { ProdViewModel.editTemplate($data);}'>
</td>
<td>
<input type='button' value='delete' data-bind='click: function () { ProdViewModel.deleteProduct($data); }'>
</td>
</tr>
</script>
<script type="text/html" id="editTemplate">
<tr>
<td><input type='text' data-bind='value: $data.Store_of_Product' /></td>
<td><input type='text' data-bind='value: $data.Store_Product_id' disabled='disabled' /></td>
<td><input type='text' data-bind='value: $data.Name' /></td>
<td><input type='text' data-bind='value: $data.Subname' /></td>
<td><input type='text' data-bind='value: $data.Imgname' /></td>
<td><input type='text' data-bind='value: $data.Price' /></td>
<td><input type='text' data-bind='value: $data.Product_Discount' /></td>
<td><input type='text' data-bind='value: $data.Slogan' /></td>
<td><input type='text' data-bind='value: $data.Origin' /></td>
<td><input type='text' data-bind='value: $data.Description' /></td>
<td><input type='text' data-bind='value: $data.Product_Code' /></td>
<td><input type='text' data-bind='value: $data.Category_level_1_id' /></td>
<td>
<div><label for="filePicker">Choose a file:</label><input type="file" id="filePicker"></div>
</td>
<td>
<input type="button" value="Save" data-bind="click: ProdViewModel.saveProduct" />
</td>
<td>
<input type="button" value="Cancel" data-bind="click: function () { ProdViewModel.reset(); }" />
</td>
</tr>
</script>
I know my explanation of what I'm trying to do is somehow vague, so feel free to ask questions to make things clear. My project lies here if someone wishes to check it out (dpesios, test).

Javascript does'nt work in mvc (about checkboxlist change)

I try to get selected values of checkboxlist.I wanna send values to UrunList action.Each values will be saved in Viewbag.abc then Viewbag will be sent Create view (another view).But I can't get values from checkboxlist with javascript
Script
<script>
$(document).ready(function ()
{
$('#urunsec').change(function () {
var id=$('#urunsec').value();
$ajax({
url:'Fatura/UrunList',
type:'POST',
data: { id: id },
success: function () {
alert('suc');
},
error: function (error) {
alert('error')
}
})
});
});
UrunList View
#foreach (BillApplication.Models.Urunler con in Model )
{
<tr>
<td>
<input id="urunsec" type="checkbox" name="urunsec" value="#con.UrunId.ToString()" />
<input name="urunsec" type="hidden" value="false" />
</td>
<td>#con.UrunId</td>
<td>#con.UrunAdi</td>
<td>#con.UrunFiyat</td>
<td>#con.AltkategoriId</td>
<td colspan="4"></td>
</tr>
}
<tr>
<td>
<input id="Button1" type="button" value="button" onclick="location.href = '#Url.Action("Create", new { idlist= #ViewBag.abc as List<String>})'" />
</td>
</tr>
UrunList Action
[HttpPost]
public ActionResult UrunList(string id)
{
this.UrunList(id);
List<String> idlist = new List<String>();
idlist.Add(id);
ViewBag.abc= idlist;
return RedirectToAction("Create");
}
Create View
<td><textarea id="txt_urunler" rows="2" cols="20" style="border-style:inset; width:150px; border-width:0.2em; border-color:gainsboro">
#if (#ViewBag.abc != null)
{
foreach (var i in ViewBag.abc)
{
#i
}
}
</textarea>
</td>
Create Action
public ActionResult Create(List<String> idlist)
{
string virgul = ",";
ViewBag.virgul = virgul;
if (idlist != null)
{
ViewBag.abc = idlist;
}
return View();
}
The same id may be a cause of this issue. You should try to assign different id (some unique value) to each element or you can try this:-
#foreach (BillApplication.Models.Urunler con in Model )
{
<tr>
<td>
<input type="checkbox" name="urunsec" value="#con.UrunId.ToString()" onclick="ClickMe(this);" />
<input name="urunsec" type="hidden" value="false" />
</td>
<td>#con.UrunId</td>
<td>#con.UrunAdi</td>
<td>#con.UrunFiyat</td>
<td>#con.AltkategoriId</td>
<td colspan="4"></td>
</tr>
}
<tr>
<td>
<input id="Button1" type="button" value="button" onclick="location.href = '#Url.Action("Create", new { idlist= #ViewBag.abc as List<String>})'" />
</td>
</tr>
<script>
function ClickMe(ref) {
var id=$(ref).value();
$.ajax({
url:'Fatura/UrunList',
type:'POST',
data: { id: id },
success: function () {
alert('suc');
},
error: function (error) {
alert('error')
}
})
}
</script>
This should work with your case.

set value to jquery datatable after updating row in spring mvc with backbone.js

My project having a problem that when table row button clicked it will appear on the html input typ="text" for user updation.Updation running successfully.What i need is,when user clicked update button the updated row must replace with new row + another button for again updation.
html
<h1>Time Management</h1>
<fieldset>
<h3>Update Test!</h3>
<form action="#" th:action="#{/admin/updateTest.html}"
th:object="${test}" id="formTest">
<table>
<tr>
<td>Test Name</td>
<td><input type="text" id="testName" required="required"
th:field="*{name}" disabled="disabled"/></td>
</tr>
<tr>
<td>Max No.of Questions</td>
<td><input type="text" id="questionNo" required="required"
th:field="*{maxNoQuestions}" onKeyUp="numericFilter(this);" /></td>
</tr>
<tr>
<td>Max Time</td>
<td><input data-format="hh:mm:ss" type="text" id="testTime"
required="required" th:field="*{maxTime}" />
</td>
</tr>
<tr>
<td><input type="button" value="Update" id="btnUpdate" /> <input
type="hidden" th:field="*{id}" id="hdnTestId" /></td>
<td><label id="statusMsg"
style="color: red; size: portrait; font-size: small;"></label></td>
</tr>
</table>
</form>
</fieldset>
<table id="tests"
style="cellpadding: 0px; cellspacing: 0px; border: 0px;">
<thead>
<tr>
<th width="5%">#</th>
<th align="left">Test Name</th>
<th align="left">Max No.of Questions</th>
<th align="left">Max Time</th>
<th align="left"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
below is my backbone script for updation.
script
var TimeManagementView = Backbone.View.extend({
sTable:null,
// target item.
el : $("#adminContentOuterPnl"),
render : function() {
var data = {};
// template
var compiledTemplate = _.template(timeManagementTemplate, data);
// append the item to the view's target
this.$el.html(compiledTemplate);
sTable = $('#tests').dataTable({
"aoColumns" : [ null, null, null, null, null ],
"sPaginationType" : "full_numbers"
});
//load data from db to table.
this.loadSavedTests();
},
// Event Handlers
events : {
"click #btnUpdate" : "updateTest"
},
loadSavedTests : function() {
$('#tests tbody tr').remove();
$('#tests tbody').append('<tr><td><h4>...Loading...</h4></td></tr>');
//Load the data in using jQuerys ajax call
$.ajax({
type : 'POST',
url : 'loadAllTests.html',
success: function(responseData) {
sTable.fnClearTable();
if(responseData.length > 0){
$.each(responseData, function(index,item) {
var rowCount = index+1;
sTable.fnAddData( [ rowCount,item['name'], item['maxNoQuestions'], item['maxTime'],'<input type="image" src="../resources/img/icons/edit.png" alt="Edit" onclick="editTest('+item['id']+',this); return false;" />' ]);
});
}
}
});
},
updateTest : function(){
$('#statusMsg').text("");
if($('#testName').val()==''){
$('#statusMsg').text("Test Name Can't Be Null");
return false;
}
if($('#questionNo').val()==''){
$('#statusMsg').text("Question No. Can't Be Null");
return false;
}
if($('#testTime').val()==''){
$('#statusMsg').text("Test Time Can't Be Null");
return false;
}
$('#statusMsg').text("Updating...");
$("#formTest").ajaxForm({
success : function(status) {
if (status == 1) {
// addRowToTests(status.object);
testRow.find("td").eq(0).text($('#testName').val());
testRow.find("td").eq(1).text($('#questionNo').val());
testRow.find("td").eq(2).text($('#testTime').val());
$('#testName').val('');
$('#questionNo').val('');
$('#testTime').val('');
$('#statusMsg').text("Data Updated!");
}
},
dataType : 'json'
}).submit();
}
});
return new TimeManagementView;
});
$("#formTest").ajaxForm({
success : function(status) {
console.log(status.statusCode);
if (status.statusCode == 0) {
testRow.find("td").eq(1).text('');
testRow.find("td").eq(2).text('');
testRow.find("td").eq(3).text('');
testRow.find("td").eq(4).text('');
testRow.find("td").eq(1).text($('#testName').val());
testRow.find("td").eq(2).text($('#questionNo').val());
testRow.find("td").eq(3).text($('#testTime').val());
testRow.find("td").eq(4).html('<input type="image" src="../resources/img/icons/edit.png" alt="Edit" onclick="editTest('+status.object.id+'); return false;" />');
$('#testName').val('');
$('#questionNo').val('');
$('#testTime').val('');
$('#statusMsg').text("Data Updated!");
}else{
$('#statusMsg').text("No Change");
}
},
dataType : 'json'
}).submit();

Categories