Not able to read checked status of Custom Checkbox Server Control - c#

I am not able to read the Checked status of my custom checkbox control.
I created this control so that it would rendor correctly for easy use with bootstrap.
The control renders perfectly, and I have all the function that I want/need EXCEPT being able to read the checked status of the input when the user clicks 'submit'.
Custom Server Control Code (C#):
public class InlineBootstrapCheckBox : CheckBox, IPostBackDataHandler, ICheckBoxControl
{
private string value;
private string labelCSS;
private string labelID;
public string LabelID
{
get
{
if (!string.IsNullOrEmpty(this.labelID))
{
return this.labelID;
}
else
{
return null;
}
}
set
{
this.labelID = value;
}
}
public string LabelCSS
{
get
{
if (!string.IsNullOrEmpty(this.labelCSS))
{
return this.labelCSS;
}
else
{
return null;
}
}
set
{
this.labelCSS = value;
}
}
public string Value
{
get
{
if (!string.IsNullOrEmpty(this.value))
{
return this.value;
}
else
{
throw new NotImplementedException("You must set a 'Value' for InlineBootstrapCheckBox Controls");
}
}
set
{
this.value = value;
}
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
writer.WriteLine(string.Format("<label id=\"{0}\" class=\"{1}\" for=\"{2}\">", (this.LabelID != null) ? this.LabelID : string.Concat(this.ID, "_Label"), (this.LabelCSS != null) ? string.Concat(this.LabelCSS, " checkbox-inline") : "checkbox-inline", this.ID));
writer.WriteLine(string.Format("<input type=\"checkbox\" id=\"{0}\" value=\"{1}\">", this.ID, this.Value));
writer.WriteLine(this.Text);
writer.WriteLine("</label>");
}
}
Markup Code (.ASPX):
<div class="form-group">
<label id="lblCategories" class="col-sm-3 control-label">Categories</label>
<div class="col-sm-9">
<cookout:InlineBootstrapCheckBox runat="server" ID="chkRibs" Text="Ribs" Value="1" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkChicken" Text="Chicken" Value="2" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkBrisket" Text="Beef Brisket" Value="3" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkPork" Text="Pork" Value="4" />
<cookout:InlineBootstrapCheckBox runat="server" ID="chkAnythingBut" Text="Anything But" Value="5" />
</div>
</div>
Code Behind (C#):
This is where I think my problem is?
protected void btnSubmit_Click(object sender, EventArgs e)
{
ProRegistration regInfo = new ProRegistration();
regInfo.TeamName = this.txtTeamName.Text.ToString();
regInfo.ContactName = this.txtContactName.Text.ToString();
regInfo.StreetAddress = this.txtContactAddress.Text.ToString();
regInfo.City = this.txtContactCity.Text.ToString();
regInfo.State = this.txtContactState.Text.ToString();
regInfo.ZipCode = this.txtContactZip.Text.ToString();
regInfo.Email = this.txtContactEmail.Text.ToString();
regInfo.Phone = this.txtContactPhone.Text.ToString();
regInfo.IsRibs = this.chkRibs.Checked;
regInfo.IsChicken = this.chkChicken.Checked;
regInfo.IsBrisket = this.chkBrisket.Checked;
regInfo.IsPork = this.chkPork.Checked;
regInfo.IsAnythingBut = this.chkAnythingBut.Checked;
regInfo.Created = DateTime.Now;
DataManager.InsertProfessionalRegistration(regInfo);
}
...So basically what I need is to be able to get a positive response when I try to submit this object to my database. Currently, no matter the click status, I get a false result.
I have been trying to research an answer to this for about 3 hours now to no avail.
Thank you!

I don't know bootstrap but it looks like you are injecting an html checkbox into the output. If this is the case it will not be recognized as a server control on postback, however you can get its value by using the request.form object.
string result=Request.Form["thecheckboxid"];

Related

numerictextboxtargetelement does not exist in current context

also getting error on TargetElement also does not exist, getting args.event only no TargetElement exist
<SFNumericTextBox TValue="int?" Value="10" CssClass="e-custom" ShowSpinButton="true" Change="OnValueChange" />
#code {
private void OnValueChange(ChangeEventArgs args)
{
if (args.TargetElement == NumericTextBoxTargetElement.SpinUp)
{
}
else if (args.TargetElement == NumericTextBoxTargetElement.SpinDown)
{
}
else
{
}
}
}
You can use the ValueChange event for your requirement. The ValueChange event triggers when the NumericTextBox value is changed.
For your scenario, you can compare the previous value with the current value of the NumericTextBox component and then perform your own logic operations based on the result.
#using Syncfusion.Blazor.Inputs
<div style="margin:130px auto;width:300px">
<SfNumericTextBox TValue="int?" Value="10" CssClass="e-custom" ShowSpinButton="true">
<NumericTextBoxEvents TValue="int?" ValueChange="OnValueChange"></NumericTextBoxEvents>
</SfNumericTextBox>
</div>
#code
{
private void OnValueChange(ChangeEventArgs<int?> args)
{
var TempVlaue = args.PreviousValue;
bool result = args.Value > args.PreviousValue ? true : false;
if (result)
{
// Do something if spin up button clicked
}
else
{
// Do something if spin down button clicked
}
}
}
Numeric Textbox ValueChange: https://blazor.syncfusion.com/documentation/numeric-textbox/events#valuechange
List of Native events supported by Numeric Textbox: https://blazor.syncfusion.com/documentation/numeric-textbox/native-events#list-of-native-events-supported
Also, you can refer to the below sample for more information:
https://www.syncfusion.com/downloads/support/directtrac/general/ze/NumericTextBox1682455549

Upload image as bytearray in ASP.NET

I try to upload a file in a form in ASP.NET, my form is
<form metod="post" asp-controller="Home" asp-action="FormPage">
<input type="text" asp-for="Name" />
<input type="file" asp-for="Image" accept="image/*" />
</form>
and the model is:
class MyCLass {
public int Id { get; set; }
public string Name { get; set; }
public byte[] Image { get; set }
}
but when I select a file for the image-input, I get that it is not a valid input when i submit. Are there ways to solve it?
But, why do you care how or what the file being up-loaded is?
I mean, with any simple fileupload control, once the post-back has occured, you have the "in memory" file, and you are 100% free to convert to a byte() array at that point time. Why even bother or have the client side have to do any of that mumbo jumbo anyway?
I mean this:
<h3>Select file to up-load</h3>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="cmdGO" runat="server" Text="Up-load"
OnClick="cmdGO_Click" />
And then code behind:
protected void cmdGO_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
byte[] FileAsBytes;
FileAsBytes = (byte[])FileUpload1.FileBytes;
// do whatever with the byte array
MyCLass cFile = new MyCLass();
cFile.Id = 134;
cFile.Name = "Hello";
cFile.Image = FileAsBytes;
}
}
or probably better yet:
protected void cmdGO_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// do whatever with the byte array
MyCLass cFile = new MyCLass();
cFile.Id = 134;
cFile.Name = "Hello";
cFile.Image = (byte[])FileUpload1.FileBytes;
// do whatever
}
}
So, you can easy convert the file to bytes[] in the server side code.

javascript open modal window return values,, i dont get it?

I am not getting this Modal window / javascript stuff , I’m a bit of a noob I ve found tons of stuff about this trawling around
But its hard to find the answer when you lack the experience to ask the correct question.
and are not up to speed with all the jargon either
System.windows.froms.messagebox doesn’t work in a web situation.. I’ve discovered that much,,, This is an intranet application
How do I evaluate the result of the javascript function OpenDialogue() in a similar way to declaring DialogResult myVar =
I have a button event handler like this
protected void but_Comds(object sender, EventArgs e)
{
GridViewRow row = results.SelectedRow;
string crn = Convert.ToString(row.Cells[13].Text);
if (sender == but_crn)
{
checkData(row, crn);
}
}
Then some methods
private void checkData(GridViewRow row, string crn)
{
if (stuff)
{
DialogResult checkCrn = System.Windows.Forms.MessageBox.Show("a mesage",
"Data Check",
MessageBoxButtons.YesNoCancel);
if (checkCrn == DialogResult.No)
{
Do stuff;
}
if (checkCrn == DialogResult.Cancel)
{
Do other stuff;
}
}
else
{
Do stuff instead
}
}
I can get the dialogue to run easy enough as a child page but I can’t work out capture the return value from the child page.
I have been trying to wrap it into a method amongst other things
And I can see this doesn’t work because ClientScript.RegisterStartupScript Is void.
protected string MsgDialogue()
{
Return ClientScript.RegisterStartupScript(this.GetType(),
"newWindow", String.Format("<script>OpenDialog();</script>"));
}
I have also tried okClicked(object sender, eventargs e) methods in the childs code behind
And tried to write a variable into the MySession class and then get that variable in the checkData (row, crn) method
There must be some simple more elegant way of doing this without having to trawl thousands of pages
Hoping to stumble on it..
Here is my javascript on the mainpage
<script type="text/javascript">
function OpenDialog() {
// get the control values
var str1 = 'test';
// create an array with the values
var winArgs = new Array(str1);
var winSettings = 'center:yes;resizable:no;help:no;status:no;dialogWidth:250px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('child.aspx', winArgs, winSettings);
// see if the array is null
if (winArgs == null) {
window.alert('no data returned!');
}
return winArgs;
}
</script>
Here is child.aspx
<head runat="server">
<title></title>
<base target="_self"/>
<script type="text/javascript">
function GetData() {
// intialize variables and array to empty
var str1 = '';
var winArgs = new Array(str1);
// get the values as arguments and set the controls
winArgs = window.dialogArguments;
document.getElementById('TextBox1').value = winArgs[0];
}
function but_ok() {
window.returnValue = "ok";
window.close();
}
function but_cancel() {
window.returnValue = "cancel";
window.close();
}
function but_yes() {
window.returnValue = "yes";
window.close();
}
function but_no() {
window.returnValue = "no";
window.close();
}
</script>
</head>
<body onload="GetData()">
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly ="true"></asp:TextBox>
<asp:Button ID="dlg_ok" runat="server" Text=" OK " />
<asp:Button ID="dlg_cancel" runat="server" Text=" Cancel " />
<asp:Button ID="dlg_yes" runat="server" Text=" Yes " />
<asp:Button ID="dlg_no" runat="server" Text=" No " />
</div>
</form>
</body>
</html>
And child.aspx. cs
public class child : System.Web.UI.Page
{
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
protected global::System.Web.UI.WebControls.TextBox TextBox1;
protected global::System.Web.UI.WebControls.Button dlg_ok;
protected global::System.Web.UI.WebControls.Button dlg_cancel;
protected global::System.Web.UI.WebControls.Button dlg_yes;
protected global::System.Web.UI.WebControls.Button dlg_no;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dlg_ok.Attributes["onclick"] = "javascript:but_ok()";
dlg_cancel.Attributes["onclick"] = "javascript:but_cancel()";
dlg_yes.Attributes["onclick"] = "javascript:but_yes()";
dlg_no.Attributes["onclick"] = "javascript:but_no()";
}
}
}
Sorry ive posted quite a bit of code but hopefully if you can see what I’m trying to do
Then you might be able to better explain what I’m not getting.

Server side variable in client side custom validator

I have a custom validator on a page:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ControlToValidate="ddlProposer" ErrorMessage="Please select some values."
Display="Dynamic" onservervalidate="CustomValidator2_ServerValidate"
ClientValidationFunction="CustomValidator2_ClientValidate">
</asp:CustomValidator>
It must be valid, when a server-side list is not empty (or: the ListCount variable > 0). This list may change after the page has been loaded (via buttons on update panel):
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
...
There is no problem with server-side validation:
protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = this.ProposersList.Count > 0;
}
The problem is with client-side part. I've been trying something like this:
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var serverVariable = <%= ListCount %>;
alert(serverVariable);
arguments.IsValid = serverVariable > 0;
}
</script>
however, it fires only on first page load, and the ListCount variable is always 0 (so does the serverVariable).
The question is: is there an easy-way to make it working? So the Javascript gets the current value of some server-side variable?
you can use hidden variable on the page level and by setting its value from server side and validate on client side.
<input type="hidden" id="ListCount" runat="server" value="0" />
public partial class Pages_Application_Application : System.Web.UI.Page
{
protected List<IdValue> ProposersList
{
get
{
if (ViewState["proposersList"] == null)
ViewState["proposersList"] = new List<IdValue>();
return ViewState["proposersList"] as List<IdValue>;
}
set
{
ViewState["proposersList"] = value;
ListCount=value;
}
}
public int ListCount
{
get
{
return this.ProposersList.Count;
}
}
<script type="text/javascript">
function CustomValidator2_ClientValidate(source, arguments) {
var count= document.getElementById("ListCount").value;
alert(count);
arguments.IsValid = count > 0;
}
You'll have to do it in plain javascript, and there is no sens of getting the server side variable since it won't be up to date at the moment client validation will be done.
What you need is pass your ddl html element to your CustomValidator2_ClientValidate function and check if it contains option html elements, that should do the trick.

Asp.net passing values to the User control then display them

I'm trying to make a generic Search UserControl that can be given some values, based on those values the search results will display. However I'm currently trying to display the results of my values, and they always show up as my default values.
my UserControl code:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ProductSearch.ascx.cs" Inherits="..." %>
<asp:Label ID="lblSearchWord" runat="server" />
<asp:Label ID="lblSearch" runat="server" />
Code Behind:
private string _searchWord = string.Empty;
private int _search = -1;
public string SearchWord
{
get { return _searchWord; }
set { _searchWord = value; }
}
public int Search
{
get { return _search; }
set { _search = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
lblGroupId.Text = LevelId.ToString();
lblSearchWord.Text = SearchWord;
}
When I press the search button on the main aspx.cs page I do the following:
protected void btnSearch_Click(object sender, EventArgs e)
{
ucPS.SearchWord = txtProductSearch.Text;
ucPS.Search = 1
}
My aspx page contains the following
<%# Register src="UserControls/ProductSearch.ascx" tagname="ProductSearch" tagprefix="ps" %>
<ps:ProductSearch id="ucPS" runat="server" />
My problem is that I can't use Query strings as the user might have selected some other things on this page that I need to keep the state of, however I did test that one and foudn it working.
Where am I going wrong? or is there an better alternative (except for query strings).
All variables in a page are disposed at the end of the page-lifecycle. Hence SearchWord will always be initialized with the default value on every postback.
You need to persist it somewehere else, for example in a ViewState variable.
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
return "";
else
return (String)ViewState["SearchWord"];
}
set { ViewState["SearchWord"] = value; }
}
Nine Options for Managing Persistent User State in Your ASP.NET Application
public string SearchWord
{
get
{
if (ViewState["SearchWord"] == null)
ViewState["SearchWord"] = string.Empty;
return ViewState["SearchWord"];
}
set
{
ViewState["SearchWord"] = value;
}
}
and I use databind not pageload, this way your usercontrol doesn't load unless you call it.
protected override DataBind()
{
//you can add a condition here if you like
if(SearchWord != string.Empty)
lblSearchWord.Text = SearchWord;
}
to call this from aspx:
usercontrol.SearchWord = "my word";
usercontrol.DataBind();
and thats it..

Categories