How can i keep the selected tab selected even after postback - c#

I have some listed tab controls on my aspx form which is as below
<div id="tabs">
<ul>
<li>Tab A</li>
<li>Tab B</li>
<li>Tab C</li>
</ul>
<div id="tabs-1"></div>
<div id="tabs-2"><asp:Button ID="someid" runat="server"/></div>
<div id="tabs-3"></div>
</div>
The navigation on mouse click on a tab is done by the following:
<script type="text/javascript">
$(function () {
$("#tabs").tabs();
});
</script>
Now, my question is, How can i maintain the selected tab as it is even after postback.
For Example, I select Tab B that contains a Button which causes a postback on click.
After the postback occurs Tab A regians the foucs and i have to manually select Tab B for adjuvent operations.
Please help me to solve this problem.

I think this Code will help you...
<div id="tabs">
<asp:HiddenField ID="hidtab" Value="0" runat="server" />
<ul>
<li>Tab 1</li>
<li>Tab 2</li>
</ul>
<div id="tabs-1">
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click"/>
</div>
<div id="tabs-2">
<asp:Button ID="Button2" runat="server" Text="Submit" OnClick="Button2_Click"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
var st= $(this).find("input[id*='hidtab']").val();
if (st== null)
st= 0;
$('[id$=tabs]').tabs({ selected: st});
});
</script>
protected void Button1_Click(object sender, EventArgs e)
{
hidtab.Value = "0";
}
protected void Button2_Click(object sender, EventArgs e)
{
hidtab.Value = "1";
}

Initialize tabs with the cookie option specified. Sample
$(function () {
$("#tabs").tabs({ cookie: { expires: 30 } });
});
You need the jQuery Cookie plugin..

You can track it by your URL like they did in this post.
The following code is just for example and can be done a lot nicer. I used the active property from the jquery ui tabs. it works with the index of the element but perhaps its working with the #hash aswell did not test it. so in the example below i get the index of the tab and use it with active property;
<div id="tabs">
<ul>
<li>Tab A</li>
<li>Tab B</li>
<li>Tab C</li>
</ul>
<div id="tabs-1"></div>
<div id="tabs-2"><asp:Button ID="someid" runat="server"/></div>
<div id="tabs-3"></div>
</div>
<script type="text/javascript">
$(function () {
var tabsOpts = {},
activeTab, activeTabIndex,
urlCheck = doucment.location.href.split('#');
// urlCheck is an array so when there is more then one result
// there is a hash found in the URL
if( urlCheck.length > 1 ) {
activeTab = urlCheck[1];
// getting the index from the link
activeTabIndex = $("#tabs li a[href="+ activeTab +"]").index();
// create new object options for the tabs
tabsOpts = { active: activeTabIndex };
}
$("#tabs").tabs(tabsOpts)
.find('li a').each(function() {
// get URL from the tab href
var href = $.data(this, 'href.tabs');
// set URL with the href from your tab
document.location = href;
});
});
</script>

Client Side solution:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(IniciaRequest);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
var currentTab;
function IniciaRequest(sender, arg) {
var _Instance = Sys.WebForms.PageRequestManager.getInstance();
if (_Instance.get_isInAsyncPostBack()) {
window.alert("Existe un proceso en marcha. Espere");
arg.set_cancel(true);
}
}
function BeginRequestHandler(sender, args) {
//Persiste el valor del indice del TAB actual del control Jquery para mantener el tab actual seleccionado luego del Postback.
if ($get('hdCurrentTab') != null) {
currentTab = $get('hdCurrentTab').value;
}
//----
}
function EndRequestHandler(sender, args) {
//Permite visualiza el control JQuery TAB dentro de ventanas modales AJAX.
if (sender._postBackSettings.panelsToUpdate != null) {
$("#tabs").tabs();
//Persiste el valor del indice del TAB actual del control Jquery para mantener el tab actual seleccionado luego del Postback.
if ($get('hdCurrentTab') != null) {
$get('hdCurrentTab').value = currentTab;
$("#tabs").tabs({ active: currentTab });
}
//----
}
//----
}
</script>
HTML on Page:
<input id="hdCurrentTab" type="hidden" value="0" />
<div id="tabs" style="width:97%;margin: auto; font-family: verdana, tahoma, arial, sans-serif; font-size: 11px;">
<ul>
<li>TAB1</li>
<li>TAB2</li>
</ul>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
</div>
TAB remains selected after postbacks.

Related

Why do `JQuery` tabs lose styling after a button click

I am using JQuery tabs in my Asp.Net/C# app.
I am modelling my approach after this article. The JQuery is outside of my
<asp:UpdatePanel ID="UpdatePanel1"...></asp:UpdatePanel>
wrapper while the html components are inside.
Whenever I click a button, my tabs completely lose their CSS styling and I see all of the tab contents, rather than just the
<div id="current-tab">
for that tab.
Why is this happening and how do I fix it?
My guess is that its related to post-back or the update panel somehow, but I am not sure why the added C# code under page_load doesn't keep the selected tab current on post-back when the button is fired.
ASPX
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
...
</script>
....
<table>
<tr>
<td style="padding: 5px;">
<div id="tabs">
<ul>
<li>Tier 1</li>
<li>Tier 2</li>
<li>Tier 3</li>
<li>Tier 4</li>
</ul>
<div class="tab-content">
<div id="tab-1">
...
</div>
<div id="tab-2">
...
</div>
<div id="tab-3">
...
</div>
<div id="tab-4">
...
</div>
</div>
</div>
<asp:HiddenField ID="selected_tab" runat="server" />
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
...
selected_tab.Value = Request.Form[selected_tab.UniqueID];
...
}
You are right, it has something to do with a Partial PostBack. So in order for jquery functions to work again you need to rebind it after the Partial PostBack is done.
<script type="text/javascript">
$(document).ready(function () {
buildTabs();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
buildTabs();
});
function buildTabs() {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
}
</script>
But the selected tab is a different story. You also need to store the active tab somewhere and re-apply it after the partial PostBack is done. See this answer for details.
But basically you need to store the active tab ID in SessionStorage, cookie or Hiddden input and re-apply it in prm.add_endRequest(function () {

Cannot see from code behind the values of Dynamically created textboxes using AngularJS

I am new to AngularJS programming. Any help would be highly appreciated.
A HTML text box will be created each time a HTML button is clicked.
In webform1.aspx submit button click even cannot capture the values entered in those text boxes.
I used request.form, loop through controls in the form1 but cannot find dynamically created controls.
How to post and see the data entered in those textboxes from code behind?
Please find the code below:
webform1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
</head>
<body>
<form id="form1" runat="`server">
<div>
<div ng-app="myApp" ng-controller="myCtrl">
<li ng-repeat="element in elements ">
<input type="text" ng-model="element.id" runat=server/>
</li>
<input type="button" value="+" ng-click="newItem()" />
</div>
</form>
</body>
<script language="JavaScript">
var app = angular. Module('myApp', []);
app.controller('myCtrl', function ($scope) {
var counter = 0;
$scope.elements = [{ id: counter, value: ''}];
$scope.newItem = function () {
if ($scope.elements[counter].value != '') {
counter++;
var str1 = 'txtdynamic';
str1 += counter;
$scope.elements.push({ id: str1, value: '' });
}
}
});
</script>
</html>
webform1.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
//get the html ng repeat textbox control values
}
Try it the right way my friend. Compare the following codes with your approach.
> demo fiddle.
View
<div ng-controller="myCtrl">
<form id="form1" runat="`server">
<div>
<div ng-app="myApp" ng-controller="myCtrl">
<li ng-repeat="element in elements">
<input type="text" ng-model="elements[element.id].value" runat=server/>
</li>
<input type="button" value="+" ng-click="newItem()" />
<input type="button" value="send" ng-click="ButtonClick()" />
</div>
</div>
</form>
</div>
AngularJS application
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
var counter = 0;
$scope.elements = [{
id: counter,
value: ''
}];
$scope.newItem = function() {
if ($scope.elements[counter].value != '') {
counter++;
var str1 = 'txtdynamic';
str1 += counter;
$scope.elements.push({
id: str1,
value: ''
});
}
}
$scope.ButtonClick = function() {
var post = $http({
method: "POST",
url: "/Home/AjaxMethod",
dataType: 'json',
data: {
id: angular.isDefined($scope.elements[0]) ? $scope.elements[0].value : null
},
headers: {
"Content-Type": "application/json"
}
});
}
});

Print Preview of gridview is not center allign

I am trying to print one gridview . For that I gave a button and on button click I call javascript for printing tha grid.
function doPrint() {
var prtContent = document.getElementById('<%= grdHistoricalData.ClientID %>');
prtContent.border = 0; //set no border here
var WinPrint = window.open('', '', 'left=50,top=100,border=1px,width=1000,textAlign=center,height=1000,toolbar=0,scrollbars=1,status=0,resizable=1');
WinPrint.document.write(prtContent.outerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
This code is working fine but only thing is that print preview of gridview data is displaying left align.Normally Girdview Data is showing center align but when we print data shows in left align.
Gridview normal appearance
Print Preview of Gridview
Please help to do center align in print preview of Gridview.
There are several solutions I use in different circumstances.
1) external file. Load a small file to a iframe and call for data from parent.
<!--print.html -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Printer version</title>
<script type="text/javascript">
window.onload = function () {
var a = this.parent.getContent();
document.body.innerHTML = a;
}
function printMe() {
window.print();
}
</script>
<link href="/Styles/print.css" media="print" rel="stylesheet" />
</head>
<body>
</body>
</html>
Parent document.
<div id="divPrint" style="display:none;">
<div class="popup">
<div style="overflow:hidden;">Printer Version
<div style="float:right;">
<input type="button" ID="btnPrnClose" value="X" onclick="return closePrint()" />
</div>
</div>
<iframe id="frPrint" style="width:100%;"></iframe>
</div>
</div>
</div>
<script type="text/javascript">
function getContent() {
return '<div>' +
'<div class="right no-print" onclick="printMe();" style="cursor: pointer;" title="Print"> \
<img alt="Print" src="/images/printer.png" /></div>' + document.getElementById('gvOuterContainer').innerHTML+ '</div>';
}
function closePrint() {
document.getElementById('divPrint').style.display = 'none';
}
function PrintMessage() {
document.getElementById('divPrint').style.display = '';
document.getElementById('frPrint').src = "print.html?a=" + Math.random();//force no-cache
return false;
}
</script>
2) Print from the page.
<style type="text/css" media="print">
*
{
border: none!important;
}
.noprint,.popup
{
display: none!important;
}
#scrollContainer
{
width: auto!important;
}
.pop-show
{
display: table!important;
left: 0;
margin-left: 0;
top: 0;
width: 100%!important;
z-index: 100;
}
/* and so on */
</style>
Details may differ.
Finally got answer , I need to set gridview property that resolve this issue
<asp:TemplateField ItemStyle-HorizontalAlign="Center">

jQuery in .net validate dropdownlist, fadein and fadeout panels

I have a dropdownlist control ddlAffilation, a panel pnlForms, a panel Complete, a button Submit, a button Return.
I have a validationcontrol on the dropdownlist.
here is my jquery code
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function () {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
});
$("#<%= Return.ClientID %>").click(function () {
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(800).fadeIn('slow');
});
});
</script>
I have 2 problems:
1) With this jQuery code, I can go back and forth (fade out pnlForms, fade in Complete when click on Submit and vice versa when click on Return) only when i don't choose any value in the dropdownlist box. If I choose any value in the dropdownlist, the Return button doesn't work.
2) The jquery code bypass the .net server validation control. I need the code not do anything if no value is selected from the dropdownlist. I have tried
var isValid = true;
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
isValid = false;
return false;
}
if (isValid == true) {
...
but it doesn't work. What's the best way to do this?
Thanks,
==================================================================================
I can't add an answer to my own question so I reply to John here:
Thanks John. I have my code like this and it solves problem 2.
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#<%= Return.ClientID %>").click(function () {
alert('blah2');
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(800).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
});
</script>
However, problem 1 still exists. Let me clarify. I have a few textboxes, a dropdownlist and a submit button to collect feedback from the users. They are all in the panel pnlForms.
All controls can be empty except for the dropdownlist. We took care of this using your code and a server validation control.
when the users click the submit button, I want the pnlForms to fadeOut and a hidden panel called pnlComplete to fadeIn. The pnlComplete has a text saying thanks for the feedback and a button called Return that let the users send another feedback.
When the users click on the Return button, the opposite happens here. The pnlComplete fadeOut and the pnlForms fadeIn.
The Submit button works well but the Return button doesn't work at all. I set some alert() inside the Return.click(function but it doesn't hit.
Any ideas?
Here is the code of the whole page.
<%# Page Title="" Language="C#" MasterPageFile="~/Master.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="content" runat="Server">
<asp:UpdatePanel ID="pnlForms" runat="server">
<ContentTemplate>
<fieldset>
<legend>Your Information</legend>
<ol>
<li>
<label for="ctl00_content_name">
Your Name:</label>
<asp:TextBox ID="Name" runat="server" Width="150px"></asp:TextBox>
<em class="optional">Optional </em></li>
<li>
<label for="ctl00_content_status">
Your Affiliation:*</label>
<asp:DropDownList ID="ddlAffilation" runat="server" Width="155px">
<asp:ListItem Text="--Select One--" Value="" Selected="True" />
<asp:ListItem>F</asp:ListItem>
<asp:ListItem>S</asp:ListItem>
<asp:ListItem>T</asp:ListItem>
</asp:DropDownList>
<em class="required">Required
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage=" - Please select your affiliation"
ControlToValidate="ddlAffilation" SetFocusOnError="True" ForeColor=""></asp:RequiredFieldValidator>
</em></li>
</ol>
</fieldset>
<div style="text-align: center;">
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="submit_Click" /></div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="Complete" style="display: none;">
<asp:UpdatePanel ID="pnlComplete" runat="server">
<ContentTemplate>
<p>Thank you</p>
<div style="text-align: center;">
<asp:Button ID="Return" runat="server" Text="Return" /></div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Content>
<asp:Content ID="Content3" runat="server" ContentPlaceHolderID="cpClientScript">
<script type="text/javascript">
$(document).ready(function () {
$("#<%= Submit.ClientID %>").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#<%= pnlForms.ClientID %>").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#<%= Return.ClientID %>").click(function () {
$("#Complete").fadeOut('slow');
$("#<%= pnlForms.ClientID %>").delay(1000).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
});
</script>
</asp:Content>
I'm not sure if I read your question right or not, but if your issue is that you don't want the jquery to continue firing and allow the form to submit if the dropdown is empty do this:
Instead of attaching a .click event to your button, attach a .submit event to your form. Then you want to use e.PreventDefault() to stop the main submit execution if its not valid
Eg:
$("#FORMNAME").submit(function(e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
// Submitting form...
}
function IsValid() {
// Add any other validation in here
if ($("#<%= ddlAffilation.ClientID %>").val() == "") {
return false;
}
return true;
}
Also, you should ALWAYS do server validation along with your client validation.. otherwise all someone has to do is directly submit / bypass your javascript checks
Edit for your edit:
Is the return button being created dynamically or is it there on page load? If its dynamic, its probably never getting assigned to in your jquery, as it doesn't exist when it runs.
Here is a quick test you could try:
var returnButton = $("#<%= Return.ClientID %>");
alert(returnButton.attr("id");
If you don't get back the ID of your return button, its not matching up in your code and thats why your click event isn't working. If thats the case, do a view source on your page and find out what the actual return button ID is set to (this is easier with FireBug or similar tool)
Adding this as a separate answer since its just a huge chunk of code that isn't exactly related to the original answer, but does work as intended. I took the code you gave and converted to basic html from asp.net, and it does work correct, does it work for you?
Could you try posting the output from the asp.net page instead of the code itself? Maybe something isn't being set right on the button element's ID.
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js" type="text/javascript"></script>
</head>
<body>
<div ID="Content1">
<div ID="pnlForms">
<fieldset>
<legend>Your Information</legend>
<ol>
<li>
<label for="ctl00_content_name">
Your Name:</label>
<textbox ID="Name" runat="server" Width="150px"></TextBox>
<em class="optional">Optional </em></li>
<li>
<label for="ctl00_content_status">
Your Affiliation:*</label>
<select ID="ddlAffilation" Width="155px">
<option Value="" Selected="True">--Select One--</option>
<option>F</option>
<option>S</option>
<option>T</option>
</select
</li>
</ol>
</fieldset>
<div style="text-align: center;">
<Button ID="Submit" Value="Submit" OnClick="submit_Click">Submit</Button></div>
</div>
<div id="Complete" style="display: none;">
<div ID="pnlComplete">
<p>Thank you</p>
<div style="text-align: center;">
<Button ID="Return" Value="Return">Return</Button></div>
</div>
</div>
</div>
<div ID="Content3">
<script type="text/javascript">
$(document).ready(function () {
$("#Submit").click(function (e) {
if (IsValid() == false) {
e.preventDefault();
return false;
}
else {
$("#pnlForms").fadeOut('slow');
$("#Complete").delay(800).fadeIn('slow');
}
});
$("#Return").click(function () {
$("#Complete").fadeOut('slow');
$("#pnlForms").delay(1000).fadeIn('slow');
});
function IsValid() {
// Add any other validation in here
if ($("#ddlAffilation").val() == "") {
return false;
}
return true;
}
});
</script>
</div>
</body>
</html>

Javascript - Check checkbox if Multiple Checkboxes selected

I was wondering if someone could help me with some javascript as I'm quite unfamilar with it and unfortunately have been tasked with writing a function for tomorrow, and I appear to be failing miserably.
In my MVC application, I have a View where the user can select multiple outlets within a particular groupHeader. Already written was SelectAll, and DeselectAll javascript functions to select all (or deselect all) outlets within a groupHeader, however I am unsure how to use these functions within other functions.
I need to limit the existing functionality which will only allow the user to select the groupHeader, and this should select all the outlets within that group. Unfortunately this part of the application affects other parts so the underlying functionality must remain the same.
What I would ideally like is to have javascript to do the following:
If the groupHeader checkbox is checked, call the selectAll function.
If the groupHeader checkbox is unchecked, call the deselectAll function.
As the selections need to be remembered, which would be figured out from the controller, it would also be necessary to have the following functions:
On page load, if all outlets are checked in particular section, check the groupHeader checkbox.
On page load, if all outlets are unchecked in particular section, uncheck the groupHeader checkbox.
Here is the view:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.1.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="/Scripts/FormHelpers.js" type="text/javascript"></script>
<script type="text/javascript">
function selectAll(sectionId) {
toggle(sectionId, "checked");
}
function deselectAll(sectionId) {
toggle(sectionId, null);
}
function toggle(sectionId, checked) {
$('[section$=' + sectionId + ']').each(function () { $(this).attr('checked', checked); });
}
</script>
<div>
<% int i = 0; %>
<% Html.BeginForm(); %>
<% { %>
<% foreach (App.Web.Models.OutletGroup g in Model.Groups) %>
<% { %>
<div style="width:700px;">
<div style="border-bottom: 1px solid;">
<div style="font-weight: bold; font-size: larger; width: 300px; float: left;">
<input type="checkbox" id="GrpHdr" /> <%: g.GroupHeader%>
</div>
<div style="line-height: 18px; vertical-align: middle; width: 250px; float: left;">
<a id="select" href="javascript:selectAll(<%: i %>)" <%: ViewData["GROUP_ALL_SELECTED_" + g.GroupHeader] %>>
Select All</a> / <a id="deselect" href="javascript:deselectAll(<%: i %>)" <%: ViewData["GROUP_ALL_SELECTED_" + g.GroupHeader] %>>
Deselect All</a>
</div>
<div style="clear: both;">
</div>
</div>
</div>
<div style="margin-left: 10px; margin-top: 10px;">
<% foreach (App.Data.Outlet outlet in g.Outlets) %>
<% { %>
<div style="float: left; line-height: 18px; padding: 2px; margin: 2px; vertical-align: middle;
border: 1px solid grey; width: 282px;">
<input type="checkbox" section="<%: i %>" name="OUTLET_<%: outlet.OutletID %>" <%: ViewData["OUTLET_" + outlet.OutletID] %>
style="vertical-align: middle; padding-left: 5px;" />
<%= Html.TrimTextToLength(outlet.Name)%>
</div>
<% } %>
</div>
<div style="clear: both; margin-bottom: 5px;">
</div>
<% i++; %>
<% } %>
<br />
<br />
<div class="buttonFooter">
<input type="submit" value="Update" />
</div>
<div style="clear: both;">
</div>
<% } %>
</div>
</asp:Content>
Here is the controller code also:
public class OutletsController : Controller
{
public ActionResult Index()
{
// Get all the outets and group them up.
//
ModelContainer ctn = new ModelContainer();
var groups = ctn.Outlets.GroupBy(o => o.Header);
OutletViewModel model = new OutletViewModel();
foreach (var group in groups)
{
OutletGroup oGroup = new OutletGroup()
{
GroupHeader = group.Key,
};
model.Groups.Add(oGroup);
}
foreach (var group in model.Groups)
{
group.Outlets = ctn.Outlets.Where(o => o.Header == group.GroupHeader).ToList();
}
// Get the existing details and check the necessary boxes (only read undeleted mappings).
//
var currentOutlets = ctn.UserOutlets.Where(uo => uo.UserID == UserServices.CurrentUserId && !uo.Deleted);
foreach (var outlet in currentOutlets)
{
ViewData["OUTLET_" + outlet.OutletID] = "checked='checked'";
}
return View(model);
}
[HttpPost]
public ActionResult Index(FormCollection formValues)
{
// Update the existing settings.
//
ModelContainer ctn = new ModelContainer();
var outlets = ctn.UserOutlets.Where(uo => uo.UserID == UserServices.CurrentUserId);
foreach (var outlet in outlets)
{
outlet.Deleted = true;
outlet.UpdatedDate = DateTime.Now;
outlet.UpdatedBy = UserServices.CurrentUserId;
}
// Save all the selected Outlets.
//
foreach (string o in formValues.Keys)
{
if (o.StartsWith("OUTLET_"))
{
UserOutlet uo = new UserOutlet();
uo.UserID = UserServices.CurrentUserId;
uo.OutletID = int.Parse(o.Substring("OUTLET_".Length));
uo.CreatedDate = DateTime.Now;
uo.CreatedBy = UserServices.CurrentUserId;
ctn.UserOutlets.AddObject(uo);
}
}
ctn.SaveChanges();
return RedirectToAction("Index");
}
}
I'd be very grateful if anyone could offer some help, or point me in the right direction.
Thanks!
EDIT:
Edited the javascript to include the following as suggested by Tejs:
$('.GrpHdr').each(function()
{
var elements = $(this).find('input[name|="OUTLET_"]');
var checkboxCount = elements.filter(':checked').length;
if (checkboxCount == elements.length)
$('.GrpHdr').attr('checked', this.checked);
else if (checkboxCount == 0)
$('.GrpHdr').attr('checked', !this.checked);
});
However I can't seem to get this to work for me. Can anyone see what's going wrong?
First, you need to change the GrpHdr checkbox to use a class or something; currently, it looks like you generate multiple checkboxes with the same Id which is never good. Assuming you change it to a class like so:
<input type="checkbox" class="GrpHdr" />
Then you can write something like this to check the checked status:
$('.GrpHdr').each(function()
{
var elements = $(this).find('input[name|="OUTPUT_"]');
var checkboxCount = elements.filter(':checked').length;
if(checkboxCount == elements.length)
// All Checked, Do Some Logic
else if(checkboxCount == 0)
// None checked, do some logic
else
// Some Checked and some not checked
});

Categories

Resources