C# DropDownList SelectedValue is set but not saving? - c#

I feel like I'm missing something really obvious. :)
C# ASPX page, testing in most recent version of Chrome.
Here's the relevant code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="JobSearch.aspx.cs" Inherits="GCWebForms.Jobs.JobSearch" %>
<asp:Content ID="HeadContent" ContentPlaceHolderID="Head" runat="server">
<style>
a img{border: none;}
ol li{list-style: decimal outside;}
div#container{width: 780px;margin: 0 auto;padding: 1em 0;}
div.side-by-side{width: 100%;margin-bottom: 1em;}
div.side-by-side > div{float: left;width: 50%;}
div.side-by-side > div > em{margin-bottom: 10px;display: block;}
.clearfix:after{content: "\0020";display: block;height: 0;clear: both;overflow: hidden;visibility: hidden;}
</style>
<link rel="stylesheet" href="../Content/chosen.css" />
</asp:Content>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<div class="body-content">
<div id="searchform" class="simplelayoutform">
<div>
<div>
<asp:label id="lblCustomerSearch" runat="server" Text="Jobs for Customer:" AssociatedControlID="cboCustomerID" />
<asp:DropDownList ID="cboCustomerID" runat="server" class="chzn-select"
DataSourceID="DataSourceCustomer" DataTextField="CustomerName" DataValueField="CustomerID">
</asp:DropDownList>
<gcctl:MyCheckBox ID="chkCustomersShowInactive" Text="Show Inactive?" Checked="false" AutoPostBack="true" runat="server" />
</div>
</div>
[[cut - search results go here]]
</div>
<asp:SqlDataSource ID="DataSourceCustomer" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnString %>"
SelectCommand="SELECT NULL AS [CustomerID]
, NULL AS [CustomerName]
UNION SELECT [CustomerID]
,[CustomerName]
FROM [dbo].[Customers]
WHERE ((#ShowInactive = 0 AND IsActive = 1) OR (#ShowInactive = 1))
ORDER BY CustomerName">
<SelectParameters>
<asp:ControlParameter Name="ShowInactive" Type="Boolean" ControlID="chkCustomersShowInactive" PropertyName="Checked" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="JQScripts" runat="server">
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("PageForm").target != "_blank") return;
opener.document.getElementById("PageForm").target = "";
opener.document.getElementById("PageForm").action = opener.location.href;
}
</script>
<script src="../Scripts/chosen.jquery.js" type="text/javascript"></script>
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({ allow_single_deselect: true }); </script>
</asp:Content>
JobSearch.aspx.cs (relevant parts):
namespace GCWebForms.Jobs
{
public partial class JobSearch : System.Web.UI.Page
{
int? iCustomerID;
int? iStaffID;
bool bolIsPostBack = false;
//--------
protected void SetIDs()
{
this.iCustomerID = null;
this.iStaffID = null;
if (Request.QueryString["customerid"] != null) //new customer
{
try
{
this.iCustomerID = Convert.ToInt32(Request.QueryString["customerid"]);
}
catch { }
}
if (Request.QueryString["staffid"] != null) //new customer
{
try
{
this.iStaffID = Convert.ToInt32(Request.QueryString["staffid"]);
}
catch { }
}
if (iCustomerID != null)
{
this.cboCustomerID.SelectedValue = this.iCustomerID.ToString();
}
if (iStaffID != null)
{
this.cboStaffID.SelectedValue = this.iStaffID.ToString();
}
}
//--------
protected void DoSearch()
{
//gvJobsDataSource.SelectParameters["CustomerSearch"].DefaultValue = cboCustomerID.SelectedValue.ToString();
//gvJobsDataSource.SelectParameters["StaffSearch"].DefaultValue = cboStaffID.SelectedValue.ToString();
//gvJobsDataSource.SelectParameters["ShowClosed"].DefaultValue = chkShowClosed.Checked.ToString();
if(string.IsNullOrEmpty(this.cboCustomerID.SelectedValue.ToString()) && string.IsNullOrEmpty(this.cboStaffID.SelectedValue.ToString()))
{
SearchPrompt.Visible = this.bolIsPostBack;
gvJobs.DataSourceID = "gvJobsDataSourceInit";
} else
{
SearchPrompt.Visible = false;
gvJobs.DataSourceID = "gvJobsDataSource";
}
gvJobs.DataBind();
}
//--------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetIDs();
DoSearch();
}
this.bolIsPostBack = true;
}
//--------
protected void btnSearch_Click(object sender, EventArgs e)
{
DoSearch();
}
Issue: When I run, for example, http://server/Jobs/JobSearch?customerid=22, it's supposed to load customerID 22 into a dropdownlist of customers. And then it's supposed to do a search on that customer. It does the first thing, but not the second.
That is, I can SEE that the customer with the ID 22 has been automatically selected in the dropdownlist. But when I step through the PageLoad routine, it runs SetIDs(), where it does set this.cboCustomerID.SelectedValue = '22', but then when it runs DoSearch() and I put a watch on this.cboCustomerID.SelectedValue.ToString(), it returns '', and so no search is run.
Why is this.cboCustomerID.SelectedValue.ToString() returning '' when I just set its value to '22'?
Many thanks!

Related

DropdownList Linked to a Textbox

I am trying to display the selectedIndex of my dropdownlist in the textBox (field number 2) and in my ajax htmlEditor (field number 3). I already can show field number 1 on my dropdown, but I cant seem to show anything on the other boxes, all I get are errors :(, implying that the dataSource has not any items which is weird. Here are my classes.
Messages.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Messages.aspx.cs" Inherits="ASF.HC.JobApplication.Admin.Messages" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Messages</h2>
<asp:ScriptManager ID="ScriptManager2" runat="server"></asp:ScriptManager>
<legend>Pick the template to use:</legend>
<asp:dropdownlist id ="ddlTemplate" runat ="server" Height="38px" Width="397px">
<asp:listitem value ="1"> Juan Valdez </asp:listitem >
<asp:listitem Value ="2"> Querido bebe</asp:listitem>
</asp:dropdownlist >
<p> </p>
<asp:TextBox ID="textDos" AutoPostBack="true" runat="server" MaxLength="40"></asp:TextBox>
<ajaxToolkit:HtmlEditorExtender ID="textoTemplate" runat="server" TargetControlID="txtDetails"
EnableSanitization="false" DisplaySourceTab="true" >
</ajaxToolkit:HtmlEditorExtender>
</asp:Content>
Message.aspx.cs
public partial class Messages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
loadList();
}
public void loadList()
{
try
{
BO.Messages template = new BO.Messages();
ddlTemplate.DataSource = template.GetAll();
ddlTemplate.DataValueField = "Title";
DataSet ds = new DataSet("Templates");
ddlTemplate.DataSource = ds;
ddlTemplate.DataBind();
ddlTemplate.SelectedIndexChanged += DdlTemplate_SelectedIndexChanged;
textDos.Text = ds.Tables[0].Rows[0]["id"].ToString();
} catch (Exception e)
{
}
}
private void DdlTemplate_SelectedIndexChanged(object sender, EventArgs e)
{
//when we change the dropdownlist we need to get the student id and set it to the textbox
DropDownList mydropdownlist = sender as DropDownList;
textDos.Text = mydropdownlist.SelectedValue;
}
}
Been checking this error all day long, with no plausible answer and can not detect what am I doing wrong.
Thanks for your assistance.

How to get a URL file name without extension in a webmethod

I have this URL (mydomain.com/mypage.aspx). I want to get the file name "mypage" only in a webmethod. I tried the following code but I only get the name of the function itself (MyMethod). I don't get the name of the page from the URL. Any help is well appreciated.
EDIT
To be more specific the webmethod resides in a user control so using FilePath OR PhysicalPath would give me the name of the UserControl file name (MyUserControl) and not the aspx page (mypage) in the URL.
mypage.aspx
<asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder" runat="server">
<uc:myUserControl runat="server" />
</asp:content>
myUserControl.cs
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
Convert.ToString(HttpContext.Current.Request.Url)));
} }
OR
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
HttpContext.Current.Request.RawUrl));
} }
OR
public static string PageName { get {
return (string)(Path.GetFileNameWithoutExtension(
HttpContext.Current.Request.PhysicalPath));
} }
[WebMethod]
public static string MyMethod()
{
StringBuilder SBstring = new StringBuilder();
SBstring.Append(PageName);
return SBstring.ToString();
}
Just use FilePath like this:
var fi = new FileInfo(HttpContext.Current.Request.FilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fi.Name);
Complete working solution for required structure (Master Page -> Content Page -> User Control
Site Master
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebTester.Site1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Webform1.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebTester.WebForm1" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
</asp:Content>
Webform1.aspx.cs:
namespace WebTester
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string ProcessIT(string name, string address)
{
return WebUserControl1.ProcessIT(name, address);
}
}
}
WebUserControl1.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebTester.WebUserControl1" %>
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something is wrong.');
}
}
</script>
<div>
<p>Please enter data:</p>
Name<br />
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
Address<br />
<asp:TextBox ID="txtaddress" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="HandleIT(); return false;" />
</div>
WebUserControl1.ascx.cs:
namespace WebTester
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public static string ProcessIT(string name, string address)
{
var fi = new FileInfo(HttpContext.Current.Request.FilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fi.Name);
string result = string.Format("Name '{0}' and address '{1}' came from Page '{2}'", name, address, fileNameWithoutExtension);
return result;
}
}
}

FileUpload Null reference error

I want to use FileUpload Control to save Image to Database. The HasFiles return always false after I click on BtnSave. I tried with and without UpdatePanel but could not find the solution.
My code is:
protected void BtnSave_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
var ChNumber = txtNumber.Text;
string img = this.FileUpload1.PostedFile.FileName;
//Save image to database function
}
else
{
lblStatus.Text="Image not Uploaded";
}
}
Try with a simple form without UpdatePanel. Here's the markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="BtnSave" runat="server" Text="Button" OnClick="BtnSave_Click" />
<asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
<asp:Label ID="lblStatus" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
</html>
And here's the code:
using System;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnSave_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
var ChNumber = txtNumber.Text;
string img = this.FileUpload1.PostedFile.FileName;
//Save image to database function
}
else
{
lblStatus.Text = "Image not Uploaded";
}
}
}
I set a brekapoint at if (FileUpload1.HasFile == true) and see the uploaded file is there.

Cannot Unregister UpdatePanel exception with Cross Page Posting

I am getting the dreaded exception "Cannot unregister UpdatePanel with ID 'UpdatePanel' since it was not registered with the ScriptManager" when trying to combine a popup window and some Cross-Page Posting. I've been able to reproduce the problem with a small example.
I have seen other questions that handle the Unload event for the UpdatePanel, but that doesn't seem to work with the addition of the Cross Page Posting.
How do I get around this issue?
To duplicate the issue with the code below:
Start the Setup page
Press the View Popup link
Close the popup
Press the Next button to transfer to the Target page
Press the Back button to transfer to the Setup page
Press the View link and close the popup
Press the Next button, and see the failure
Here are the highlights (forgive the length, but it should be cut-and-pastable):
Setup.aspx
<head runat="server">
<title>Setup </title>
<script type="text/javascript">
function openCenteredWindow(url, height, width, name, parms) {
//Snip setting up window location stuff
var win = window.open(url, name, winParms);
return win;
}
</script>
</head>
<body>
<h1>Setup Page</h1>
<form id="aspnetForm" runat="server">
<div>
<asp:TextBox ID="txtData" runat="server" Width="80%" Text="<%# Information %>" />
<br />
<asp:LinkButton ID="lbViewData" runat="server"
OnClientClick="aspnetForm.target='ViewDataPopup';"
Text="View In Popup" /> <br />
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click" />
</div>
<div>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:updatepanel ID="UpdatePanel" runat="server" OnUnload="UpdatePanel_Unload"></asp:updatepanel>
</div>
</form>
</body>
Setup.Aspx.cs
public partial class Setup : System.Web.UI.Page
{
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (this.ViewState["Information"] != null)
_Information = this.ViewState["Information"].ToString();
}
protected override object SaveViewState()
{
this.ViewState["Information"] = _Information;
return base.SaveViewState();
}
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null && PreviousPage is TargetPage)
{
_Information = ((TargetPage)PreviousPage).SetupData;
}
else if (!Page.IsPostBack)
{
_Information = String.Format("This test started at {0}", DateTime.Now);
}
Page.DataBind();
lbViewData.PostBackUrl = "ViewData.aspx?u=0";
lbViewData.Attributes.Add("onclick", "JavaScript:openCenteredWindow(\"ViewData.aspx?u=0\", 400, 300, \"ViewDataPopup\", 'scrollbars=yes');");
}
private string _Information;
public string Information
{
get { return _Information; }
}
protected void btnNext_Click(object sender, EventArgs e)
{
HttpContext.Current.Server.Transfer("~/TargetPage.aspx");
}
}
ViewData.aspx
<%# PreviousPageType VirtualPath="~/Setup.aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
<title>View Data</title>
<script type="text/javascript">
function fixForm() {
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = "";
}
</script>
</head>
<body onload="fixForm()">
<form id="aspnetForm" runat="server">
<div>
<h2 >View Data</h2>
</div>
<asp:Label ID="lblData" runat="server" Text="<%# SetupData %>" />
</form>
</body>
ViewData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
Setup setup = (Setup)PreviousPage;
this.SetupData = setup.Information ?? "Data not set in Setup Page";
}
Page.DataBind();
}
private string _setupData = "Did not get updated data";
protected string SetupData
{
get { return _setupData; }
set { _setupData = value; }
}
TargetPage.aspx
<%# PreviousPageType VirtualPath="~/Setup.aspx" %>
<body style="background-color: #9999BB">
<h1>Target Page</h1>
<form id="aspnetForm" runat="server">
<div>
<asp:Label ID="lblData" runat="server" Text="<%# SetupData %>" /><br />
<asp:Button ID="btnBack" runat="server" Text="Back" OnClick="btnBack_Click" />
</div>
</form>
</body>
TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (this.PreviousPage == null)
Response.Redirect("Setup.aspx");
this.SetupData = PreviousPage.Information;
}
Page.DataBind();
}
public string SetupData
{
get { return ViewState["SetupData"].ToString(); }
set { ViewState["SetupData"] = value; }
}
protected void btnBack_Click(object sender, EventArgs e)
{
HttpContext.Current.Server.Transfer("~/Setup.aspx");
}
As you can see, it's enough to have the UpdatePanel just sitting on the page and doing nothing for this error to occur.

Checkboxes checked value ever false in repeater

I am newbie with ASP .NET. I am using a repeater with parent checkboxes (User Type) and inside alse i am using other repeater control for to show User Type Divisions.
Because Checkbox Microsoft ASP control don´t have a value I am using html input type checkboxes because i need perform any actions with javascript and jquery.
My code is the next:
ASPX CODE
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Admin/Admin.Master"
CodeBehind="Editar.aspx.cs" Inherits="ELearning.Admin.Cursos.Editar" ValidateRequest="true" %>
<%# Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<title>Editar Curso</title>
<script type="text/javascript" src="../../js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="../../js/funcionesGenerales.js"></script>
<script type="text/javascript" src="../../ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="../../ckfinder/ckfinder.js"></script>
<script type="text/javascript">
window.onload = function () {
//editor = CKEDITOR.replace('editor');
CKFinder.setupCKEditor(null, '../../ckfinder/');
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" EnablePageMethods="true" />
<h2 class="principalTitle">
<asp:Label runat="server" ID="lblID"></asp:Label>
</h2>
<div>
<h2>
Titulo:
<asp:TextBox runat="server" Width="500px" ID="txtTitulo"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfTitulo" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="txtTitulo"></asp:RequiredFieldValidator>
<%--<asp:RequiredFieldValidator ID="rfvTitulo" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="txtTitulo" />--%>
<asp:RegularExpressionValidator ID="maxLenTxtTitulo" ControlToValidate="txtTitulo"
CssClass="Validator" ValidationExpression="(\s|.){0,256}$" Text="El titulo es demasiado largo. La longitud máxima es de 256."
runat="server" />
</h2>
</div>
<div>
<h2>
Objetivos:
<asp:RequiredFieldValidator ID="rfvObjetivos" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="heObjetivos" />
</h2>
<p>
<CKEditor:CKEditorControl ID="heObjetivos" Width="862px" runat="server"></CKEditor:CKEditorControl>
</p>
</div>
<div>
<h2>
Destinatarios:
<asp:RequiredFieldValidator ID="rfvDestinatarios" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="heDestinatarios" /></h2>
<p>
<CKEditor:CKEditorControl ID="heDestinatarios" Width="862px" runat="server"></CKEditor:CKEditorControl>
</p>
</div>
<h2>
Modalidad del curso
<asp:RequiredFieldValidator ID="rfvModalidad" CssClass="Validator" Text="El campo es obligatorio"
runat="server" ControlToValidate="heModalidad" />
</h2>
<p>
<CKEditor:CKEditorControl ID="heModalidad" Width="862px" runat="server"></CKEditor:CKEditorControl>
</p>
<h2>
Tipos de usuario que lo pueden ver</h2>
<ul>
<asp:Repeater ID="rptTipoUsuarios" runat="server">
<ItemTemplate>
<li class="listItems">
<input type="checkbox" id="chkTipoUsuario" class='<%# "chkTipoUsuario-" + DataBinder.Eval(Container.DataItem, "TipoUsuarioId") %>'
value='<%# DataBinder.Eval(Container.DataItem, "TipoUsuarioId") %>' runat="server"
onclick="seleccionarTodos($(this).is(':checked'), $(this).attr('id'))" />
<span id="nombreTipoUsuario" class='<%# "nombreTipoUsuario-" + DataBinder.Eval(Container.DataItem, "TipoUsuarioId") %>'>
<%# DataBinder.Eval(Container.DataItem, "Nombre") %>
</span>
<ul>
<asp:Repeater ID="rptDivisiones" runat="server">
<ItemTemplate>
<li class="listSubItems"><span class='<%# "chkDivision-" + DataBinder.Eval(Container.DataItem, "TipoUsuarioId")%>'>
<input type='checkbox' id="chkDivision" class='<%# "chkDivision-class-" + DataBinder.Eval(Container.DataItem, "DivisionId")%>'
value='<%# DataBinder.Eval(Container.DataItem, "DivisionId") %>' runat="server"
onclick="sumarCheckeo($(this).attr('class'))" />
<%# DataBinder.Eval(Container.DataItem, "Nombre") %>
</span></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
<div>
<h2>
<span style="display: none">
<asp:TextBox ID="contadorCheckeos" ClientIDMode="Static" Text="0" runat="server"></asp:TextBox>
<asp:CheckBox ID="chkAuxOtros" ClientIDMode="static" runat="server" />
</span>
<asp:RegularExpressionValidator CssClass="Validator" ID="revChkQuantity" ControlToValidate="contadorCheckeos"
runat="server" Text="Debe seleccionar al menos 1 division" ValidationExpression="[1-9]*\.?[0-9]*[1-9]">
</asp:RegularExpressionValidator>
</h2>
</div>
<div>
<asp:Button runat="server" ID="btnSubmit" Text="Actualizar"></asp:Button>
</div>
</asp:Content>
CODE BEHIND
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ELearning.Admin.Cursos
{
public partial class Editar : System.Web.UI.Page
{
private ELearningContextDataContext db;
private int cursoId;
private List<DataObject.CursoDivision> cursoDivisiones;
protected void Page_Load(object sender, EventArgs e)
{
DeclararHandlers();
InicializarConexionDB();
((Admin)this.Master).PermitirORedireccionarAdmin();
Int32.TryParse(Request.QueryString["id"], out cursoId);
if(!((from p in db.Cursos where p.CursoId == cursoId select p).ToArray().Length > 0))
Response.Redirect("Default.aspx");
if (!Page.IsPostBack)
{
CargarColecciones();
CargarDatos();
}
}
protected void CargarColecciones()
{
CargarTiposDeUsuario();
CargarDivisiones();
}
protected void CargarTiposDeUsuario()
{
var tipoUsuarios = DataObject.TipoUsuario.ObtenerTodos(db, false);
rptTipoUsuarios.DataSource = tipoUsuarios;
rptTipoUsuarios.DataBind();
}
protected void CargarDivisiones()
{
var divisiones = DataObject.Division.ObtenerTodos(db);
}
protected void InicializarConexionDB()
{
db = new ELearningContextDataContext();
}
protected void DeclararHandlers()
{
btnSubmit.Click += new EventHandler(btnSubmit_Click);
rptTipoUsuarios.ItemDataBound += new RepeaterItemEventHandler(rptTipoUsuarios_ItemDataBound);
}
protected void rptTipoUsuarios_ItemCreated(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = (RepeaterItem)e.Item;
if (ri.ItemType == ListItemType.Item ||
ri.ItemType == ListItemType.AlternatingItem)
{
Repeater rptDivisiones = (Repeater)ri.FindControl("rptDivisiones");
rptDivisiones.ItemCreated += new RepeaterItemEventHandler(rptDivisiones_ItemCreated);
}
}
protected void rptTipoUsuarios_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var chk = (System.Web.UI.HtmlControls.HtmlInputCheckBox)e.Item.FindControl("chkTipoUsuario");
chk.ID = "chkTipoUsuario-" + e.Item.ItemIndex;
if (string.Compare(((ELearning.TipoUsuario)(e.Item.DataItem)).Nombre.ToLower(), "otros") == 0)
{
//Ver si se checkeo
//Se puede crear un enum para los tipo de usuario y las divisiones
Int32.TryParse(Context.Request.QueryString["id"], out cursoId);
var query = from p in db.CursoDivisiones where p.CursoId == cursoId && p.DivisionId == 8 select p;
if (query.ToArray().Length > 0)
{
chk.Checked = true;
chkAuxOtros.Checked = true;
}
}
//((System.Web.UI.HtmlControls.HtmlInputCheckBox)chk).Checked = false;
Repeater ChildRepeater = (Repeater)e.Item.FindControl("rptDivisiones");
LlenarRepeaterInterno(ChildRepeater, ((ELearning.TipoUsuario)e.Item.DataItem).TipoUsuarioId);
}
}
protected void LlenarRepeaterInterno(Repeater childRepeater, int tipoUsuarioId)
{
/*SELECT * FROM Divisiones INNER JOIN TipoUsuarios as tu on tu.TipoUsuarioId = Divisiones.TipoUsuarioId WHERE Divisiones.TipoUsuarioId = 1 AND tu.Nombre != 'Otros'*/
var query = (from p in db.Divisiones join q in db.TipoUsuarios on p.TipoUsuarioId equals q.TipoUsuarioId where p.TipoUsuarioId == tipoUsuarioId && string.Compare(q.Nombre.ToLower(), "Otros".ToLower()) != 0 select p).Distinct();
childRepeater.DataSource = query;
childRepeater.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//CODE FOR SUBMIT
}
catch (Exception ex)
{
//Manejar excepcion
}
}
protected List<DataObject.CursoDivision> CrearCursoDivision()
{
try
{
List<DataObject.CursoDivision> divisiones = new List<DataObject.CursoDivision>();
int divisionId;
int tipoUsuarioId;
foreach (RepeaterItem item in rptTipoUsuarios.Items)
{
var checkboxTipoUsuario = (System.Web.UI.HtmlControls.HtmlInputCheckBox)item.FindControl("chkTipoUsuario");
Int32.TryParse(checkboxTipoUsuario.Value, out tipoUsuarioId);
if (!DataObject.TipoUsuario.esOtros(db, tipoUsuarioId))
{
Repeater rptDivisiones = (Repeater)item.FindControl("rptDivisiones");
if (rptDivisiones != null)
{
foreach (RepeaterItem itemDivision in rptDivisiones.Items)
{
var checkbox = (System.Web.UI.HtmlControls.HtmlInputCheckBox)itemDivision.FindControl("chkDivision");
if (checkbox.Checked)
{
Int32.TryParse(checkbox.Value, out divisionId);
divisiones.Add(new DataObject.CursoDivision(0, divisionId));
}
}
}
}
else
{
if (chkAuxOtros.Checked)
{
var query = db.Divisiones.Single(q => q.TipoUsuarioId == tipoUsuarioId);
divisiones.Add(new DataObject.CursoDivision(0, query.DivisionId));
}
}
}
return divisiones;
}
catch (Exception ex)
{
throw ex;
}
}
protected void CargarDatos()
{
try
{
Int32.TryParse(Context.Request.QueryString["id"], out cursoId);
//CKFinder.FileBrowser _fileBrowser = new CKFinder.FileBrowser();
//_fileBrowser.BasePath = "/ckfinder/";
//_fileBrowser.SetupCKEditor(null);
if (!Page.IsPostBack && cursoId != 0)
{
var curso = db.Cursos.Single(p => p.CursoId == cursoId);
lblID.Text = string.Format("Editando Curso ID #{0}", cursoId.ToString());
txtTitulo.Text = curso.Titulo;
heObjetivos.Text = curso.Descripcion;
heModalidad.Text = curso.Modalidad;
heDestinatarios.Text = curso.Destinatario;
var query = from q in db.CursoDivisiones
where q.CursoId == cursoId
select q.DivisionId;
string divisionesSeleccionadas = string.Join(",", query.ToArray());
Page.ClientScript.RegisterStartupScript(GetType(), "JSScript", string.Format("tildar('{0}')", divisionesSeleccionadas), true);
}
else
{
if (cursoId == 0)
Response.Redirect("Default.aspx");
}
}
catch (Exception ex)
{
//REdirige hacia pagina de error
}
}
}
}
My problem is that the parent checkbox ever is in false state in Checked property.
Also This page don`t perform correctly the validation actions. When i write in Firebug console validation asp function also return true state.
Which could be the problems?
Thanks in advance
Finally I use a simple html input tag for checkbox adding the onserverclick attribute.
Therefore not is necessary the autopostback.
Thanks and excuse me.
Accept suggestions in comments.

Categories

Resources