A checkbox to select / unselect them all - c#

I want to create a checkbox that will have the "power" to check / uncheck a checkboxfor for each items presents in a list.
Here is part of the view as I built it right now (please bear with the false names and convention):
<p>
#using (Html.BeginForm("SendObj", "Manager"))
{
<p>
Select / UnSelet All Items #Html.CheckBox("selectAll", true)
</p>
<table id="objToSend">
<tr>
<th>Obj Name</th>
<th>Number In Stock</th>
(...)
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.DisplayFor(x => x[i].m_OthObj.m_ObjName)</td>
<td>#Html.DisplayFor(x => x[i].m_NbInStock)#Html.HiddenFor(x => x[i].m_NbInStock)</td>
(...)
<div id="divChckBox">
<td>
#Html.CheckBoxFor(x => x[i].m_IsSelected)
</td>
</div>
</tr>
}
</table>
<input type="submit" value="Send"/>
}
</p>
As for the "how", well, I have searched a bit around and I have tried this jquery script, but to no avail:
**** EDIT ****
Here's a new jQuery based on the comments people posted below. The alerts are there on debug purpose, and both appears when needed:
<script type="text/javascript">
$(document).ready(function() {
alert("The document is ready");
$("#selectAll").click(function() {
alert("The case has been clicked");
var chkValue = $(this).is(":checked");
$("#divChckBox").attr("checked", "checked");
});
});
</script>
I do not mind using jquery, far from it, I just do not know how it works yet. Maybe that's why what I have in mind does not work.
Can anyone help me out? Thank you!
* EDIT *
I will add here what the rendered page gives out for the checkboxes:
<td><input checked="checked" class="chckBoxList" data-val="true" data-val-required="The m_IsSelected field is required." name="[0].m_IsSelected" type="checkbox" value="true" /><input name="[0].m_IsSelected" type="hidden" value="false" /></td>
Maybe that will give out more informations on what's going on.

#Html.CheckBox("TheOneCheckBoxToRuleThemAll")
Change your current checkbox code to:
<td>#Html.CheckBoxFor(x => x[i].m_IsSelected, new{ #class = "checkGroup1"})</td>
The easiest Jquery ever (make sure to put it in document.ready like shown):
<script type="text/javascript">
$(document).ready(function () {
//alert("the document is ready");
$("#TheOneCheckBoxToRuleThemAll").click(function () {
//alert("inside my click event");
var chkValue = $(this).is(":checked");
$(".checkGroup1").prop("checked", chkValue);
});
});
</script>
EDIT:
My previous answer used the .attr() attribute. After testing, I had all sorts of trouble getting that to work. After referring to this SO post, I switched to using .prop() and everything magically began to function correctly.
Jquery .Attr()
Jquery .Prop()
EDIT:
In the example I've provided, your checkboxes MUST look like this:
<input name='itdoesnotmatter' id='donotcare' class='checkGroup1' />
also, do not use that stupid name that I put on there, use something easy like
#Html.CheckBox("MasterCheck")

I stand corrected: CheckBoxFor does NOT allow class setting
In your Helper
<div id="divChckBox">
#Html.CheckBoxFor(x => x[i].m_IsSelected)
</div>
And then make your selector group by the class:
$("#divChckBox :checkbox").attr("checked", "checked");

As there are MANY comments around and many answers, here's my current code (which works!):
<script type="text/javascript">
$(document).ready(function() {
//alert("The document is ready");
$("#selectAll").click(function() {
//alert("The case has been clicked");
var chkValue = $(this).is(":checked");
$(".divChckBox").prop("checked", chkValue);
});
});
</script>
<p>
#using (Html.BeginForm("SendObj", "Manager"))
{
<p>
Select / UnSelet All Items #Html.CheckBox("selectAll", true)
</p>
<table>
<tr>
<th>Card Name</th>
<th>Number In Stock</th>
(...)
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.DisplayFor(x => x[i].m_OthObj.m_ObjName)</td>
<td>#Html.DisplayFor(x => x[i].m_NbInStock)#Html.HiddenFor(x => x[i].m_NbInStock)</td>
(...)
<td>
<input type="checkbox" name="itdoesnotmatter" class="divChckBox" checked="true"/>
</td>
</tr>
}
</table>
<input type="submit" value="Send"/>
}
</p>
Now every checkboxes are checked or not depending on the state of the select all checkboxes! Thank you everyone.
Now I need to solve the problem of "unlinking" the result of the checkbox in my controller because a behavior was linked to this. But it's another problem.

Related

ASP.NET MVC - Open Table in new window and print

I'm using ASP.NET MVC and have a table with 9 columns which shows results from the database where the user can filter values based on columns. The table structure looks like this:
<table class="tableMain" id="x">
<thead>
<tr class="trMain">
<th class="thMain">
#Html.DisplayNameFor(model => model.ID)
</th>
<th class="thMain">
#Html.DisplayNameFor(model => model.YEAR)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class="trMain">
<td class="tdMain">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td class="tdMain">
#Html.DisplayFor(modelItem => item.YEAR)
</td>
<td class="tdMain">
<input type="checkbox" class="chkCheckBoxId" name="airlineId" value="#item.ID" />
</td>
<td class="tdMain">
#Html.ActionLink("EditValue", "Edit", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
Now I need a button, so that the dynamically generated table opens in a new window and the print dialog opens automatically. I had this piece of code:
<div class="line-btn">
<input type="submit" value="print" onclick="printTable()" class="btn fl btn-print">
</div>
<script language="javascript">
function printTable()
{
var printContent = document.getElementById("x");
var windowUrl = 'about:blank';
var num;
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();var printWindow = window.open(num, windowName, 'left=50000,top=50000,width=0,height=0');
printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
</script>
The problem here is that the table is completely unsorted when printed so the rows/columns are shifted.
I found this example:
https://datatables.net/extensions/buttons/examples/print/simple.html
This is exactly what I need (open the table in a new window and open print dialog). But unfortunately this sample has a lot of code in the javascript files that I don't need. There is a search field included and a pagination.
Can someone help me please? Thank you very much!
Ok I found a good solution.
This is the code I used:
<script src="#Url.Content("~/Scripts/jquery-3.5.1.js")" type="text/javascript"></script>
<script>
var myApp;
myApp = (function (app) {
$('#x').click(function () {
myApp.print();
});
app.print = function () {
$.ajax({
url: 'Home/Print',
success: function (data) {
if (myApp.arePopupsBlocked()) {
alert('please allow popups.');
}
var printWindow = window.open();
if (printWindow) {
$(printWindow.document.body).html(data);
} else {
alert('please allow popups.');
}
},
error: function () {
alert('Error');
}
});
};
app.arePopupsBlocked = function () {
var aWindow = window.open(null, "", "width=1,height=1");
try {
aWindow.close();
return false;
} catch (e) {
return true;
}
};
return app;
})(window.myApp || {})
</script>
and right before the table-tag the link to click:
<style>
/* suppress link for printing */
##media only print {
a {
display: none;
}
}
</style>
[print table]
There opens no new window but the table is well formated for printing.

create multi instance backward-timer jquery plugin in MVC razor?

i have page view list like
#foreach (var item in Model)
{
<tr>
<td class="colcode">
#Html.DisplayFor(modelItem => item.SMCode)
</td>
<td class="colname">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="colip">
#Html.DisplayFor(modelItem => item.IP)
</td>
<td class="coloffsetfund">
<div>
<span id="#item.IP.Replace(".","")"></span>
</div>
<div>
<span id="#item.SMCode"></span>
</div>
<script type="text/javascript">
$(document).ready(function () {
idtimer = '##item.IP.Replace(".","")';
password = '#item.Password';
ip = '#item.IP';
smcode = '#item.SMCode';
startTimer(idtimer);
$(idtimer).backward_timer({
seconds: '#item.DelaySecond',
on_exhausted: function (timer) {
alert('stop timer:' + idtimer);
//ajax call to update value
}
});
});
</script>
My list have 2 items but i dont know why. when event on_exhausted of timer excute, it always is the last item. i dont know what is logic here.How do I alert correct idtimer. thanks for your help!!!
sry guys,
i knew where is my problem, because i use variable to assign value, and when generated HTML, the variable always contain lastest value. i fixed it when use direct call like
$('##item.IP.Replace(".","")').backward_timer({
for other guy get problem same me :)
thank you.

Checkbox (model) dosn't change value when checked

Ive made some checkboxes in a View. The checkboxes is implemented via the ViewModel with bool properties. I'm currently trying to change a query in the controller to "date" or "month" depending if the checkbox has been checked. However in the Controller it always jumps the the "else statement" even if "Month" has been checked. Month is always False.
I suspect the JavaScript code might be wrong.
This User Interface:
In my Controller method i try to do the following:
Controller:
var request = GoogleAnalyticsService.Data.Ga.Get("ga:59380223", start, end, "ga:visitors");
var request = GoogleAnalyticsService.Data.Ga.Get("ga:59380223", start, end, "ga:visitors");
if (model.Month)
{
request.Dimensions = "ga:month";
request.Sort = "-ga:month";
}
else
{
request.Dimensions = "ga:date";
request.Sort = "-ga:date";
}
request.MaxResults = 10000;
Google.Apis.Analytics.v3.Data.GaData d = request.Execute();
In The view ive implemented my Viewmodel and tried writing some javascript checking if what checkbox have ´been checked and if to return true or false:
View:
<table class="adminContent">
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.StartDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.StartDate)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.EndDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.EndDate)
</td>
</tr>
<tr>
<td class="data" colspan="2">
#Html.CheckBoxFor(model => model.Date, new { id = "Day" }) // -- Checkbox Date
#Html.LabelFor(model => model.Date)
</td>
</tr>
<tr>
<tr>
<td class="data" colspan="2">
#Html.CheckBox("chkMonth", new { #onclick = "updatemyhidden(this)" }) // -- Checkbox Month
#Html.HiddenFor(model => model.Month, new { id = "Month" })
#Html.LabelFor(model => model.Month)
</td>
</tr>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.GAStatisticsId ):
</td>
<td class="adminData">
#Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
<input type="button" id="GAStatisticsReport-Submit" class="t-button" value="#T("Admin.Common.Search")" />
</tr>
</table>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="/Scripts/jquery.min.js"></script>
<script type="text/javascript">
$("#GAStatisticsReport-Submit").click(function () {
if ($("select[name='GAStatisticsId'] option:selected").text() == "Visitors Report")
drawChartVisitors()
if ($("select[name='GAStatisticsId'] option:selected").text() == "Orders Report")
drawChartOrders()
if ($("select[name='GAStatisticsId'] option:selected").text() == "Conversion Report")
drawConversion()
function updatemyhidden(chkbox) {
$("#Month").val(chkbox.checked);
}
})
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
function drawChartVisitors() {
$.get('/GAStatistics/GetVisitors', {
StartDate: $('##Html.FieldIdFor(model => model.StartDate)').val(),
EndDate: $('##Html.FieldIdFor(model => model.EndDate)').val(),
},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Date');
tdata.addColumn('number', 'Visitors');
for (var i = 0; i < data.length; i++) {
if ($("#Month").is(":checked")) {
var dateStr = data[i].Date.substr(0, 4);
}
else {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
}
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
The if-statements in the controller dosnt seem to operate depending on what i select in the view.
Note: im not using httpPost/get as the data is loaded with Google Charts and i don't want the whole page to re-aload each time a new request is selected.
Is because you set bool field on the month so it will rendered as true/false for your checkbox. You have a look at the rendered HTML for the month checkbox., and no matter you checked or not the data still send back to server as true/false depend what been set when rendering the page. This value will never change.
So i suggest you either add one more property in your viewmodel to keep try check/unchecked state and in the view rendered it as hidden field and update this hidden field whenever checkbox is ticked/unticked.
Or the month field render as hidden field and add one more checkbox in the page to update the month field when checkbox is checked/unchecked
Let say we use 2nd approach, the code will look something like this, (I did not test the code below). I hope this helps:
#Html.CheckBox("chkMonth", new { #onclick = "updatemyhidden(this)" })
#Html.HiddenFor(model => model.Month)
<script type="text/javascript">
function updatemyhidden(chkbox) {
$("#Month").val(chkbox.checked);
}
</script>

strikethrough text in a foreach?

I'm using ASP.NET MVC4 and C# for a small web application. Its use is for creating a simple to-do list. What I'm struggling with is that I've got a list of tasks displayed in a foreach. With each task is a checkbox, and basically when the checkbox is clicked (i.e true) then the text should have a strike through it. I tried to use Javascript but it did not work. Here is my code:
#foreach (var item in Model)
{
<tr style="border: 1px solid;">
<td>
<input type="checkbox" name="checkbox" onchange="taskDone(#item.Id)" />
</td>
<td>
<p id="#item.Id">#Html.DisplayFor(modelItem => item.TaskDetails)</p>
</td>
</tr>
}
and Javascript:
<script language="javascript" type="text/javascript">
function taskDone(id) {
var c = document.getElementById(id);
if (this.checkbox.checked) {
c.className = "strike";
}
else {
c.className = "nostrike";
}
}
</script>
and the bit of CSS:
.strike
{text-decoration: line-through;}
could someone explain where I'm going wrong. thanks
Problem is (this.checkbox.checked) which does not refer the checkbox element
Pass the checkbox id mychekbox as second paramter into taskDone(), get that element and validate that it's checked or not by if(checkBox.checked),
<input id="mychekbox" type="checkbox" name="checkbox" onchange="taskDone(#item.Id, 'mychekbox')" />
function taskDone(id, checkBoxId) {
var c = document.getElementById(id);
var checkBox = document.getElementById(checkBoxId); //getting checkbox
if (checkBox.checked) { //validating checked or not
c.className = "strike";
}
else {
c.className = "nostrike";
}
}

Check if a checkbox is checked in a list of items

I'm building an MVC app and right now my view generates a pack of items. The user needs to check a checkbox if he wants to send the data.
Here's my view and how it is builded:
<script type="text/javascript">
$(document).ready(function() {
//alert("The document is ready");
$("#selectAll").click(function() {
//alert("The case has been clicked");
var chkValue = $(this).is(":checked");
$(".divChckBox").prop("checked", chkValue);
});
});
</script>
<p>
#using (Html.BeginForm("SendObj", "Manager"))
{
<p>
Select / UnSelet All Items #Html.CheckBox("selectAll", true)
</p>
<table>
<tr>
<th>Card Name</th>
<th>Number In Stock</th>
(...)
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.DisplayFor(x => x[i].m_OthObj.m_ObjName)</td>
<td>#Html.DisplayFor(x => x[i].m_NbInStock)#Html.HiddenFor(x => x[i].m_NbInStock)</td>
(...)
<td>
<input type="checkbox" name="itdoesnotmatter" class="divChckBox" checked="true"/>
</td>
</tr>
}
</table>
<input type="submit" value="Send"/>
}
</p>
So you understand why I cannot use "CheckboxFor". Now what I want to do is send only the items which checkbox status is "checked". I know how to do this via model binding (checkboxfor), but I'm clueless as to how to build this.
I need to return a list of items. So how could I do this? Thank you very much!
Your form will return the values based on name, so shoot whoever told you such a stupid name :)
Use
<input type="checkbox" name="InStock" class="divChckBox" checked="true" value="#Model[i].ID" />
Or something more representative. Note that it is CRITICAL that you supply a unique identifier as the value of your checkbox. The value is how you will identify what was checked!
In your controller, there's several ways you can capture it. I do it like this:
public ActionResult Create(List<int> InStock)
{
foreach(var inStockItem in InStock)
{
//do what you need to do
}
}
The important points:
List<int> InStock
This must match the NAME attribute on your checkbox. The actual values will be the Value of your checkboxes.
Here I just randomly selected Create for your Action, but you need to make it match whatever action you are in (Edit, Index, etc..)
Good Luck!
try using the attr method to change the property checked.
$(document).ready(function() {
$("#selectAll").click(function() {
var chkValue = $(this).is(":checked");
$(".divChckBox").attr("checked", chkValue);
});
});
View code:
<!-- note "x[i].m_id"; Use the entity's id property is here
...maybe this should be m_NbInStock? -->
<input type="checkbox" name="selectedItems" value="#x[i].m_id" class="divChckBox" checked="true"/>
Controller code:
public class Manager : Controller
{
/* ... */
[HttpPost]
public ActionResult SendObj(IList<Int32> selectedItems)
{
// Grab those items by their IDs found within `selectedItems` and perform
// any processing necessary
// ...
//return View();
}
/* ... */
}

Categories

Resources