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

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.

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) {
}
});
});

How can I select all checkboxes in mvc

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); }};

How to prevent insert a duplicate record in Angularjs

I am loading all records from a SQL db table using Angular and web API, what I am trying to do is to prevent the user from inserting a new record in Angular in case some of the data is duplicated with other records returned data, before going to the API.
How to raise an alert to notify and tension the user when press save that there are some fields are already exist like "code", "L_Desk", "A_Desc "with the loaded data from the table.
HTML:
<body ng-app="ContractT" ng-controller="crudController">
<br /><br />
<input type="checkbox" ng-model="Hide" />Hide <input type="button" value="Clear" ng-click="resetform()" />
<input type="submit" value="Save" ng-click="save()"/> <input type="button" value="Delete" ng-click="delete(selectedMember.sys_key)" />
<fieldset>
<legend>Contract Type</legend>
<table>
<tr>
<td>Code</td>
<td><input type="text" size="10" pattern="^[a-zA-Z0-9]+$" title="Alphnumeric" required autofocus ng-model="selectedMember.Code.Staff_Type_Code">
<input type="text" size="10" hidden ng-model="selectedMember.sys_key" /> </td>
</tr>
<tr>
<td>Latin Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Latin.L_Desc"></td>
</tr>
<tr>
<td>Local Description</td>
<td><input type="text" required size="35" ng-model="selectedMember.Local.A_Desc"></td>
</tr>
<tr>
<td>No. Of Houres Per Day</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Hours_Day"></td>
</tr>
<tr>
<td>No. Of Days Per Week(s)</td>
<td><input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Days_Week"></td>
</tr>
<tr>
<td>End Of Contract By</td>
<td>
<select ng-model="selectedContract">
<option>Age</option>
<option>Number Of Years in Service</option>
</select>
</td>
</tr>
<tr>
<td>Number</td>
<td>
<input type="text" pattern="^[0-9]+$" title="Please enter numbers only" size="10" maxlength="2" ng-model="selectedMember.Num_EndWork">
<select ng-model="selectedNumber">
<option >Months</option>
<option>Years</option>
</select>
</td>
</tr>
</table>
</fieldset>
<br />
<table border="1" ng-hide="Hide">
<thead>
<tr>
<!--<th>syskey</th>-->
<th>Code</th>
<th>Latin Description</th>
<th>Local Description</th>
<th>Hours_Day</th>
<th>Days_Week</th>
<th>Num_EndWork</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="c in Contracts | filter:selectedMember.Code | filter:selectedMember.Latin | filter:selectedMember.Local ">
<td style="display:none;">{{c.sys_key}}</td>
<td>{{c.Staff_Type_Code}}</td>
<td>{{c.L_Desc}}</td>
<td>{{c.A_Desc}}</td>
<td>{{c.Hours_Day}}</td>
<td>{{c.Days_Week}}</td>
<td>{{c.Num_EndWork}}</td>
</tr>
</tbody>
</table>
</form>
Controller :
contractT.controller('crudController', function ($scope, crudService)
{
loadrecords();
function loadrecords()
{
crudService.getContracts().then(function (response) {
$scope.Contracts = (response.data);
$scope.selectedMember = {};
console.log($scope.Contracts);
});
}
$scope.save = function () {
debugger;
if ($scope.selectedContract == 'Age' && $scope.selectedNumber == 'Months') {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 1,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else if ($scope.selectedContract == 'Age' && $scope.selectedNumber == 'Years')
{
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 2,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else if ($scope.selectedContract == 'Number Of Years in Service' && $scope.selectedNumber == 'Months') {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 3,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
else {
var Contract = {
Staff_Type_Code: $scope.selectedMember.Code.Staff_Type_Code,
L_Desc: $scope.selectedMember.Latin.L_Desc,
A_Desc: $scope.selectedMember.Local.A_Desc,
Num_EndWork: $scope.selectedMember.Num_EndWork,
Type_EndWork: 4,
Hours_Day: $scope.selectedMember.Hours_Day,
Days_Week: $scope.selectedMember.Days_Week,
sys_key: $scope.selectedMember.sys_key
}
}
if (!$scope.selectedMember.sys_key) {
var promisePost = crudService.post(Contract);
promisePost.then(function (pl) {
loadRecords();
$scope.selectedmember = {};
}, function (err) {
console.log("Err" + err);
});
}
else
{
var promisePost = crudService.put(Contract);
promisePost.then(function (pl) {
loadRecords();
$scope.selectedmember = {};
}, function (err) {
console.log("Err" + err);
});
}
}
$scope.resetform = function () {
$scope.selectedMember = {};
//$scope.selectedMember = {};
//$scope.Local = {};
//$scope.Nhd = null;
//$scope.Ndw = null;
//$scope.Num = null;
}
$scope.selectedMember = { Code: "",sys_key:"", Latin:"" , Local:"", Hours_Day :"", Days_Week:"", Num_EndWork:"" }
$scope.showInEdit = function (member)
{
$scope.selectedMember = member;
//$scope.selectedMember.Code = member;
//$scope.selectedMember.Latin = member;
//$scope.selectedMember.Local = member;
//$scope.selectedMember.Hours_Day = member;
//$scope.selectedMember.Days_Week = member;
//$scope.selectedMember.Num_EndWork = member;
}
You can use filter here inorder to check for duplicates
var filtered= $filter('filter')($scope.contracts, function(value){
return value.Staff_Type_Code === Contract.Staff_Type_Code ;
});
if(filtered.length > 0){
console.log("duplicate exists");
}

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).

Get Value Checkbox Checked in MVC using Ajax Post

can somebody help me..
this is my Code:
Index.cshtml
<!DOCTYPE html>
<html>
<head>
<title>jQuery With Example</title>
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(function () {
$('.chkview').change(function () {
$(this).closest('tr').find('.chkitem').prop('checked', this.checked);
});
$(".chkitem").change(function () {
var $tr = $(this).closest('tr'), $items = $tr.find('.chkitem');
$tr.find('.chkview').prop('checked', $items.filter(':checked').length == $items.length);
});
});
function Save() {
$.ajax({
url: #Url.Action("Index", "Home" , "Index"),
type: "POST",
data: formData ,
dataType: "json",
success: function(data){
alert(data.RoleID)
},
error: function(e){
debugger;
}
}
</script>
</head>
<body>
<h2>Access Control-Home</h2>
<br />
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { RoleID="RoleID" }))
{
<input type="hidden" name="RoleID" value="1" id="RoleID" />
<table id="mytable">
<tr>
<td>View</td>
<td>Insert</td>
<td>Update</td>
<td>Delete</td>
</tr>
<tr>
<td>Administrator</td>
<td>
<input type="checkbox" class="chkview chkview-1" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-1" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-1" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-1" />
</td>
</tr>
<tr>
<td>Free User</td>
<td>
<input type="checkbox" class="chkview chkview-2" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-2" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-2" />
</td>
<td>
<input type="checkbox" class="chkitem chkitem-2" />
</td>
</tr>
</table>
<br />
<button type="submit" class="buttons buttons-style-1" onclick="Save()">Save</button>
}
</body>
</html>
HomeController.cs
[HttpPost]
public ActionResult Index(string RoleID)
{
var _roleID = RoleID;
return View();
}
i want to ask 2 question.
how i can parsing value of list checked checkbox using ajax? i want parsing classname of checkbox which i checked example i need list of array if i checked row administrator, { 'chkinsert-1','chkupdate-2' }
how i can get value collection of array in controller post?
example:
public ActionResult Index(string RoleID, array[] collChecbox) contents of collChecbox = { 'chkinsert-1','chkupdate-2'} in accordance with the user checked of checkbox input.
can somebody help me??
Why don't you use Ajax.BeginForm() this makes so easy to send posted form value.
Also, you should create proper model first.
MODEL
public class UserRole
{
public Administrator Administrator { get; set; }
public FreeUser FreeUser { get; set; }
}
public class Administrator
{
public int Checkbox1 { get; set; }
}
public class FreeUser
{
public int Checkbox1 { get; set; }
}
Do following in View.
#model Model.UserRole
<div id="result"></div>
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
<input type="hidden" name="RoleID" value="1" id="RoleID" />
<table id="mytable">
<tr>
<td>View</td>
<td>Insert</td>
<td>Update</td>
<td>Delete</td>
</tr>
<tr>
<td>Administrator</td>
<td>
#Html.CheckBoxFor(m => m.Administrator.Checkbox1)
</td>
</tr>
<tr>
<td>Free User</td>
<td>
#Html.CheckBoxFor(m => m.FreeUser.Checkbox1)
</td>
</tr>
</table>
<br />
<button type="submit" class="buttons buttons-style-1" onclick="Save()">Save</button>
}
Controller action
[HttpPost]
public ActionResult Index(UserRole model)
{
return View();
}
Also don't forget to include ajax library.
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Categories