how does one do something like this with asp.net <asp:textbox> and c #? (Thus creating an array of text boxes)
HTML:
<input name="Search[]" value="google" />
<input name="Search[]" value="yahoo" />
<input name="Search[]" value="alltheweb" />
PHP:
$array = $_GET['Search']; // or $_POST['Search'];
/*
$array is now an array like:
array(
0 => "google",
1 => "yahoo".
2 => "alltheweb"
)
/*
Since the controls will all be strongly named it would be easy to just grab them each by name, but if you need them in an array you could wrap the controls in a panel..
You could do something similar to this:
<div runat="server" id="myPanel">
<asp:TextBox runat="server" id="search1" />
<asp:TextBox runat="server" id="search2" />
<asp:TextBox runat="server" id="search3" />
</div>
Linq:
IEnumerable<string> values = myPanel.Controls.OfType<TextBox>()
.Select(textBox => textBox.Text);
Non Linq:
string[] values = new string[myPanel.Controls.Count];
for(int i = 0; i < myPanel.Controls.Count; ++i)
{
values[i] = (myPanel.Controls[i] as TextBox).Text;
}
Edited:
If you are going to dynamically add (or just have non-asp) inputs then it can actually be significantly easier to turn the inputs into an array server side.
For instance if you wish to have a bunch of <input type='text' name='search[]' /> on the page, on the server you can do the following to turn the items into a string array:
string[] inputValues = Request.Form["search[]"].Split(',');
So for the original example provided the equivalent would be:
HTML:
<input name="Search[]" value="google" />
<input name="Search[]" value="yahoo" />
<input name="Search[]" value="alltheweb" />
C#:
string[] myArray = Request.Form["search[]"].Split(',');
/*
myArray is now an array like:
0: "google"
1: "yahoo"
2: "alltheweb"
/*
You could also create the array like this:
TextBox[] textBoxes = new[] { search1, search2, search3 };
<div runat="server" id="myPanel">
<asp:TextBox runat="server" id="search1" />
<asp:TextBox runat="server" id="search2" />
<asp:TextBox runat="server" id="search3" />
</div>
It gives the same end result as Quintin's answer, but I find this easier to read.
Related
I have an asp:TextBox on a page:
<asp:TextBox ID="edEmail" runat="server" />
And the form is submitted with a normal <asp:Button> control:
<asp:TextBox ID="edEmail" runat="server" />
<asp:Button ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click" />
These are rendered into the client as:
<input name="ctl00$MainContent$edEmail" id="ctl00_MainContent_edEmail"></input>
<input name="ctl00$MainContent$bbOK" id="ctl00_MainContent_bbOK"
type="submit" value="Save User"
onclick='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$bbOK", "", true, "", "", false, false))' >
When the form is submitted through a regular <asp:Button> everything sends correctly. Reading html forms is painful, but the formatted request body is:
&ctl00%24MainContent%24edEmail = asdf%40here.net
&ctl00%24MainContent%24bbOK = Save+User
Excellent, the e-mail address is going to the server. Next we will change the type of the input box to the new html5 email type. We do this after installing the appropriate update to the .NET 4 Framework:
<asp:TextBox ID="edEmail" type="email" runat="server" />
<asp:Button ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click" />
And now we repeat the same procedure. The rendered HTML is:
<input type="email" name="ctl00$MainContent$edEmail" id="ctl00_MainContent_edEmail" >
<input name="ctl00$MainContent$bbOK" id="ctl00_MainContent_bbOK"
type="submit" value="Save User"
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$bbOK", "", true, "", "", false, false))" >
And when we submit the form, the e-mail address form input is present:
&ctl00%24MainContent%24edEmail = asdf%40here.net
&ctl00%24MainContent%24bbOK = Save+User
Excellent, the browser (both IE11 and Chrome 30-something) are submitting the contents of the form as expected.
Next we add something to the page that triggers an "auto-postback", an <asp:RadioGroup>:
<asp:TextBox ID="edEmail" type="email" runat="server" />
<asp:RadioButtonList ID="rbAccountType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="rbAccountType_IndexChanged">
<asp:ListItem>Windows</asp:ListItem>
<asp:ListItem Selected="True">Local</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click" />
This gives the rendered HTML of:
<input type="email" name="ctl00$MainContent$edEmail" id="ctl00_MainContent_edEmail" >
<input id="ctl00_MainContent_rbAccountType_0" type="radio" name="ctl00$MainContent$rbAccountType" value="Windows" checked="checked"><label for="ctl00_MainContent_rbAccountType_0">Windows</label>
<input id="ctl00_MainContent_rbAccountType_1" type="radio" name="ctl00$MainContent$rbAccountType" value="Local"
onclick="javascript:setTimeout('__doPostBack(\'ctl00$MainContent$rbAccountType$1\',\'\')', 0)">
<input name="ctl00$MainContent$bbOK" id="ctl00_MainContent_bbOK"
type="submit" value="Save User"
onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$bbOK", "", true, "", "", false, false))" >
But when this form "auto-postsback", the email field is missing:
&ctl00%24MainContent%24rbAccountType = Local&__ASYNCPOST=true&
If i change the email input's type from email to text:
<asp:TextBox ID="edEmail" runat="server" Type="text" />
the rendered radiobutton remains unaffected:
<input id="ctl00_MainContent_rbAccountType_1" type="radio" name="ctl00$MainContent$rbAccountType" value="Local"
onclick="javascript:setTimeout('__doPostBack(\'ctl00$MainContent$rbAccountType$1\',\'\')', 0)">
but the postback data now (correctly) contains exactly what it's supposed to:
&ctl00%24MainContent%24edUsername = ian
&ctl00%24MainContent%24edFullname = Ian%20Boyd
&ctl00%24MainContent%24edDescription = foo
&ctl00%24MainContent%24edEmail = asdf%40here.net
&ctl00%24MainContent%24rbAccountType = Local&__ASYNCPOST=true&
If i change it back to email:
<asp:TextBox ID="edEmail" runat="server" Type="email" />
it again fails, failing to include the email input type
&ctl00%24MainContent%24edUsername = ian
&ctl00%24MainContent%24edFullname = Ian%20Boyd
&ctl00%24MainContent%24edDescription = foo
&ctl00%24MainContent%24rbAccountType = Local&__ASYNCPOST=true&
tldr
WebForms is a buggy architecture that i should have stopped using five years ago There's no fix, and Microsoft won't, so i'm just looking for commiserating. doesn't support HTML 5.
What is WebForms doing that uses the browser to not submit all fields in a form? The failure happens in the IE and Chrome client.
Addendum
The title of this question calls out email input type. But the same bug happens for number input type; and presumably all html5 input types.
And marking up hyper-text in code:
protected void Page_Load(object sender, EventArgs e)
{
edEmail.Attributes["type"] = "email";
edEmployeeID.Attributes["type"] = "number";
...
}
does not solve it. The form still fails to submit its contained values during an "auto-postback" submit (and correctly submitting all values during a "regular" submit).
Impressive that 27 minutes after asking the question, Googling for:
asp.net autopostback not including html5 input types
only gives me as the person experiencing the problem. Apparently i'm the only person trying to shoe-horn HTML5 into WebForms.
Found the bug in the generated WebForms client side Javascript code:
ScriptResource.axd
// Name: MicrosoftAjaxWebForms.debug.js
// Assembly: AjaxControlToolkit
// Version: 3.5.50401.0
// FileVersion: 3.5.50401
// (c) 2010 CodePlex Foundation
_onFormSubmit: function PageRequestManager$_onFormSubmit(evt)
{
var count = form.elements.length;
for (i = 0; i < count; i++)
{
var element = form.elements[i];
var tagName = element.tagName.toUpperCase();
if (tagName === 'INPUT')
{
var type = element.type;
if ((type === 'text') ||
(type === 'password') ||
(type === 'hidden') ||
(((type === 'checkbox') || (type === 'radio')) && element.checked))
{
formBody.append(encodeURIComponent(name));
formBody.append('=');
formBody.append(encodeURIComponent(element.value));
formBody.append('&');
}
}
}
}
By definition, WebForms will not input HTML5 input types in the form body during a postback. It will by definition only support the few original input types:
text
password
hidden
checkbox
radio
color unsupported
date unsupported
datetime unsupported
datetime-local unsupported
email unsupported
month unsupported
number unsupported
range unsupported
search unsupported
tel unsupported
time unsupported
url unsupported
week unsupported
You supposedly need to leave your server control as an <asp:TextBox ... /> but override its type attribute in your code-behind:
edEmail.Attributes["type"] = "email";
[Source]
Is it possible to write something like this?
<input class="form-control" id="name" name="name"
placeholder='<asp:Label runat="server" ID="lblFormName"></asp:Label>' type="text" required autofocus />
Solution 1: let ASP.Net render extra attributes
You can use the native TextBox control :
<asp:TextBox runat="server"
ID="name"
required="required"
autofocus="autofocus"
CssClass="form-control"
placeholder="myplaceholder" />
Extra attributes (ones that are not properties of the TextBox class), will be rendered as is:
Html result:
<input name="ctl00$MainContent$name"
type="text"
id="MainContent_name"
class="form-control"
required="required"
autofocus="autofocus"
placeholder="myplaceholder" />
If the generated id must be explicit, you can add CliendIDMode="Static":
<asp:TextBox runat="server"
ID="name"
required="required"
autofocus="autofocus"
CssClass="form-control"
placeholder="myplaceholder"
ClientIDMode="Static" />
Result:
<input name="ctl00$MainContent$name"
type="text"
id="name"
class="form-control"
required="required"
autofocus="autofocus"
placeholder="myplaceholder" />
Solution 2: write your own control
An even better approach is to extend the textbox class:
using System.Web.UI.WebControls;
namespace WebApplication1.Controls
{
public class TextBoxEx : TextBox
{
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
if (AutoFocus) writer.AddAttribute("autofocus", "autofocus");
if (Required) writer.AddAttribute("required", "required");
if (!string.IsNullOrEmpty(PlaceHolder)) writer.AddAttribute("placeholder", PlaceHolder);
base.AddAttributesToRender(writer);
}
public string PlaceHolder
{
get {
var obj = ViewState["PlaceHolder"];
return obj != null ? (string)obj : default(string);
}
set { ViewState["PlaceHolder"] = value; }
}
public bool AutoFocus
{
get {
var obj = ViewState["AutoFocus"];
return obj != null ? (bool)obj : default(bool);
}
set { ViewState["AutoFocus"] = value; }
}
public bool Required
{
get {
var obj = ViewState["Required"];
return obj != null ? (bool)obj : default(bool);
}
set { ViewState["Required"] = value; }
}
}
}
Then you can register and use the control:
<%# Register Assembly="WebApplication1" TagPrefix="local" Namespace="WebApplication1.Controls" %>
....
<local:TextBoxEx runat="server" required="true" autofocus="true" PlaceHolder="my placeholder" />
You want to assign some value to one of HTML element's properties?
<asp:HiddenField runat="server" ID="lblFormName" />
<input class="form-control" id="name" name="name" placeholder='<%# lblFormName.Value %>' ...
Then you pass lblFormName.Value from CodeBehind.
You cannot declare a single ASP.NET control in a pure HTML page. It must be a ASP.NET page (aspx) which is processed by the server.
i have a system that generates unique numbers for reference..here is my function in jquery:
function random() {
return Math.floor(Math.random() * 100000000);
}
function generateRandomNumber() {
$("#GenerateCode").val(random());
}
window.onload = function () {
generateRandomNumber();
}
here is my mark up(asp):
<div id="step3" class="formwiz">
<h4>Step 3: Reference Number</h4>
<br clear="all" />
<p>
<label>Reference Number</label>
<span class="field">
<input type="text" id="GenerateCode" name="GenerateCode" class="smallinput" disabled="disabled" /> <small style="color: red">Please write the numbers at the back of your check</small>
</span>
</p>
</div>
this function works fine with html (input)...but when i shifted from input to ast textbox, the numbers are not posted in the textbox...do i need to use getelementbyid.?
please help...
Try using a class instead so change the class attribute to:
class="smallinput random"
and change the javascript to:
$(".random").val(random());
I would take a wild guess that you're actually using ASP.NET and not classic ASP and you try to change the text box to:
<asp:TextBox id="GenerateCode" runat="server" CssClass="smallinput" Enabled="False" />
In such case, the generated ID might be different than what you give it, if the textbox is part of control, placeholder or something like this.
To ensure same ID use ClientIDMode and set it to Static:
<asp:TextBox id="GenerateCode" runat="server" ClientIDMode="Static" CssClass="smallinput" Enabled="False" />
Now the jQuery code should work fine again.
I want to retain data in the view controls like drop down list, radio button, checkbox, textbox while displaying same view again with validation fail message. Data is in the drop down list bind using the ViewData. Check box data bind using viewdata. User enter values in the textbox and for checkbox control.
When view is displayed with the validation messages controls are reset and for drop down list data needs to be passed in the viewData before displaying view. Please let me know any solution to this.
Thanks & Regards,
Tsara.
Find the required code below
Please find below View . There is some data in the drop down list and also in the check box. For the first time page render it is passed in the ViewData.
<div id="RegisterLogin">
<label id="Label1"> Project:</label>
<%= Html.Label( Convert.ToString(ViewData["SelectedProject"])) %>
<%= Html.DropDownList("ProjectCode", (SelectList)ViewData["ddlProject"], "--Select--", new { id = "ddlProject" , title = "Select Project" })%>
<br />
<br />
<label id="Label2">
Select User:</label>
<%= Html.DropDownList("ddlUsers", (SelectList)ViewData["ddlUsers"], "--Select User--", new { id = "ddlUsers", title = "Select User" })%>
<br />
<br />
<label id="spacing">
Username:</label>
<input type="text" name="txtUserName" title="Enter username" id="txtUserName" />
<%= Html.ValidationMessage("username") %>
<br />
<br />
<label id="leftalign">
Password :</label>
<input type="password" name="txtPassword" title="Enter your password" id="txtPassword" />
<%= Html.ValidationMessage("password") %>
<br />
<br />
Confirm Password :
<input type="password" name="txtConfirmPassword" title="Confirm your password" id="txtConfirmPassword" />
<%= Html.ValidationMessage("confirmPassword") %>
<br />
<br />
<label id="space" >Email :</label>
<input type="text" name="txtEmailId" title="Enter your email id" id="txtEmailId" />
<%= Html.ValidationMessage("email") %>
<br />
<br />
<label id="rolealign"> Assign Role : </label>
<div class="listPermissions">
<%= Html.ValidationMessage("role") %>
<% Dictionary<string, string> lstRoles = ViewData["ListRoles"] as Dictionary<string, string>; %>
<% if (lstRoles != null)
{
int iCounter = 1;
foreach (KeyValuePair<String,String> item in lstRoles)
{ %>
<%= Html.CheckBoxCustom(Convert.ToString(iCounter+1), "chkRole", item.Value,"") %>
<%= Html.Encode(item.Key) %><br />
<%}
}%>
</div>
<br />
<input type="image" src="../../Content/save.jpg" value="Save" alt="Save" style="padding-left:250px;"/>
<%--<img src="../../Content/save.jpg" alt="Save" id="imageGO" />--%>
<img src="../../Content/reset.jpg" onclick="document.forms[0].reset()" alt="Reset"/>
<%--<img src="../../Content/reset.jpg" alt="Reset" onclick="return btnCancel_onclick()" />--%>
</div>
In postback function call validation is done as follows
public ActionResult Register(string txtUserName, string txtPassword, string txtConfirmPassword, string txtEmailId, FormCollection frmCollection)
{
string strValue = frmCollection.Get("chkRole");
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
if (ValidateRegistration(txtUserName, txtEmailId, txtPassword, txtConfirmPassword, frmCollection))
{
if (strValue == "")
{
ModelState.AddModelError("role", "Please select the role");
}
else
{
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(txtUserName, txtPassword, txtEmailId);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuth.SignIn(txtUserName, false /* createPersistentCookie */);
// Create an empty Profile for the newly created user
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
}
}
}
//IDictionary<string, ValueProviderResult> valueProvider = frmCollection.ToValueProvider();
//Dictionary<string, string> valueProvider = frmCollection.AllKeys.ToDictionary(k => k, v => frmCollection[v]);
//foreach (string i in valueProvider.Keys)
//{
// ModelState.SetModelValue(i, valueProvider[i]);
//}
//Get list of projects
ProjectOperations objProjectOperations = new ProjectOperations();
List<Project> lstProjects = objProjectOperations.GetAll();
//Logging://Verbose:
logEntry = new LogEntry("List of project added into view data", "AzureTableLogs", 0, 0, System.Diagnostics.TraceEventType.Verbose, "", null);
Logger.Write(logEntry);
ViewData["ddlProject"] = new SelectList(lstProjects, "ProjectCode", "ProjectName");
MembershipUserCollection lstUser = Membership.GetAllUsers();
ViewData["ddlUsers"] = new SelectList(lstUser, "UserName", "UserName");
//MembershipUserCollection lstUser= Membership.GetAllUsers();
// If we got this far, something failed, redisplay form
return View();
}
Every time before displaying view need to have values in the view data.
For resolve this i tried solution i got like
IDictionary valueProvider = frmCollection.ToValueProvider();
but it is not supported in mvc 2.0.
If you need more details please let me know.
I'm new to jQuery so this may be a real simple answer. I have a ASP.NET project that I'm trying to dynamically add content to an ASP Label element by typing into a text box and clicking a button. Sounds simple right? Well, I can get the content to added, but when the form is submitted the Label element is still empty? Why is the new data not submitted? What step am I missing? Please help. Here's some sample code:
<asp:Label ID="lblContainer" Text="" runat="server" />
<input type="text" name="tag" id="tag" />
<input type="button" name="AddTag" value="Add" class="button" onclick="addTag();" />
function addTag() {
if ($("#tag").val() != "") {
$("#lblContainer").append('$("#tag").val()' + '<br />');
$("#tag").val("");
}
}
Asp.Net doesn't work that way because it won't send the contents of a <span> tag in the HTTP Post when your form is submitted. You need to add that content to an <input> of some sort. Try something like this instead.
<span id="tagContainer" runat="server"></span>
<input type="text" name="tag" id="tag" />
<input type="button" name="AddTag" value="Add" class="button" onclick="addTag();" />
<!-- Use a hidden field to store the tags -->
<asp:HiddenField id="tagText" runat="server" />
function addTag() {
var newTag = $.trim($("#tag").val());
if (newTag != "") {
$("#tag").val("");
$("#tagContainer").append(" "+ newTag);
// append the newTag to the hidden field
var $tagText = $("#tagText");
$tagText.val($tagText.val() + " " + newTag);
}
}
Then in your asp.net code you can retrieve the value like so..
string myTagText = tagText.value;