Get posted value In C# ASP.NET - c#

I have a dynamic form that allow to add many fields dynamically,
I Know how to get the value of single field in aspnet using : Request.Form["myField"],but here i have more than field and i dont know the count of these fields since these are dynamic
the fields name is "orders[]"
ex:
<form>
<input type="text" name="orders[]" value="order1" />
<input type="text" name="orders[]" value="order2" />
<input type="text" name="orders[]" value="order3" />
</form>
In php,
i get the values as an array by accessing $_POST['orders'];
ex:
$orders = $_POST['orders'];
foreach($orders as $order){
//execute ...
}
how can I do this in c# ?

Use Request.Form.GetValues.
Request.Form is a NameValueCollection, an object that can store a collection of items under the same key and the ToString displays the values in CSV format.
Markup:
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<input type="text" name="postField[]" />
<asp:Button Text="text" runat="server" OnClick="ClickEv" />
Code behind:
protected void ClickEv(object sender, EventArgs e)
{
var postedValues = Request.Form.GetValues("postField[]");
foreach (var value in postedValues)
{
}
}

You would use Request.Form[]. Or if your form and fields had runat="server" and ids, you could just use the id in the codebehind and the .Text() method to access its value.

You can access everything that gets sent back to the server by using the Request object.
Request.Form.Items
Is a collection that will contain the item you are looking for.

Related

.NET foreach checkboxes form into controller [duplicate]

I have a list of items and I would like to delete items that are checked in a list of checkboxes.
I can't use something like CheckboxList since I'm using Grid.Mvc to display my lines. That is why I create checkboxes in each line with column.add("<input type="checkbox".....>);.
Every checkbox has its own ID:
<input type="checkbox" id="3">
<input type="checkbox" id="4">...
I would like to know how to pass all checked checkbox IDs to the controller (from there I will perform delete operations). How can I post an array of checked IDs from my form to my controller action with one button press?
Example of generated HTML:
<label><input type="checkbox" name="deletedItems" value="3"> Some label for 3</label>
<label><input type="checkbox" name="deletedItems" value="4"> Some label for 4</label>
...
<button type="submit">Submit</submit>
Controller action:
[HttpPost]
public ActionResult MyAction(int[] deletedItems)
{
// deletedItems contains all values that were checked
// when the submit button was clicked. Here you can
// loop through the array of IDs and delete by ID.
...
}
Note that the checkboxes do not have an id attribute. It is not used for model binding. Instead it has a name attribute named "deletedItems" that matches the name of the argument of the MyAction controller action, and that is what is used when model binding. The value attribute of checked checkboxes will be used to populate the deletedItems array of int[].
If you want generated html like
<label><input type="checkbox" name="deletedItems" value="3"> Some label for 3</label>
<label><input type="checkbox" name="deletedItems" value="4"> Some label for 4</label>
Then you can use the following code
<td>#Html.CheckBox("selectedItems", new { #value = #item.checkId })</td>
<td><input id="selectedItems" name="selectedItems" type="checkbox" value="11503" />
<input name="selectedItems" type="hidden" value="false" />
</td>
It won't pass selectedItems to controller.

Code echecks for DPM (Authorize.Net)

I am using asp.net, c#, and web forms (not MVC).
I was following this thread, but I am not sure what the code behind would be to implement this solution.
https://community.developer.authorize.net/t5/Integration-and-Testing/DPM-with-EChecks/m-p/33623#M181...
It states to use this for the form:
<input type='hidden' runat="server" name='x_login' id='x_login' />
<input type='text' readonly="readonly" runat="server" name='x_amount' id='x_amount' size='9' />
<input type='text' runat="server" name='x_fp_sequence' id='x_fp_sequence' />
<input type='text' runat="server" name='x_fp_timestamp' id='x_fp_timestamp' />
<input type='text' runat="server" name='x_fp_hash' id='x_fp_hash' />
<input type='hidden' name='x_method' id='x_method' value='ECHECK' />
<input type='hidden' name='x_bank_aba_code' id='x_bank_aba_code' value='?????????' />
<input type='hidden' name='x_bank_acct_num' id='x_bank_acct_num' value='123456789123' />
<input type='hidden' name='x_bank_acct_type' id='x_bank_acct_type' value='CHECKING' />
<input type='hidden' name='x_bank_name' id='x_bank_name' value='bANKnAME' />
<input type='hidden' name='x_bank_acct_name' id='x_bank_acct_name' value='aCCOUNTnAME' />
<input type='hidden' name='x_echeck_type' id='x_echeck_type' value='WEB' />
<input id="x_relay_url" name="x_relay_url" type="hidden" value="https://developer.authorize.net/tools/paramdump/index.php" />
<input type='hidden' name='x_relay_response' value='true' />
<input type='hidden' name='x_delim_data' value='false' />
<input type='submit' runat="server" id='buttonLabel' />
So my question is what is necessary in my C# code for this to work? I have been searching and haven't found resources on the topic for the DPM method. I only have seen resources for AIM.
For DPM there's not really anything you can do with fields such as "x_bank_aba_code", etc, in the code-behind because that would involve posting back to your own server, which would put you into the land of "PCI Compliance", which negates using DPM in the first place.
What I have done is:
1) Ask for all non-CC or ECHECK data on a previous page
2) Store this data and generate a GUID for the record
3) Load up all that data on your payment page from the code-behind (on PageLoad() - pass the guid on the URL so you can pull the appropriate record and display the data already entered)
4) either
name your actual input fields "x_bank_aba_code", etc. (I don't recommend this)
-or-
Attach an OnClientClick() event to your submit button (allows for validation.) Then...
5) Use the validation to load up the hidden variables.
// Routing Number
var routingNumber = $("#<%=txtBankRoutingNumber.ClientID%>").val();
var routingNumber2 = $("#<%=txtBankRoutingNumberConfirm.ClientID%>").val();
routingNumber = routingNumber.trim();
routingNumber2 = routingNumber2.trim();
if (routingNumber == '') {
alert('Please provide your Routing Number.');
return false;
}
if (routingNumber2 == '') {
alert('Please confirm Routing Number.');
return false;
}
if (routingNumber != routingNumber2) {
alert('Routing Numbers don\'t match.');
return false;
}
// THIS LINE WILL SET THE HIDDEN VARIABLE
document.getElementsByName('x_bank_aba_code')[0].value = routingNumber;
I'll try to post more detail later.
Hope this helps - but the main point is that the banking/CC/ECHECK information cannot be posted pack to your server - that's where the javascript/jquery comes in by both validating the input and loading up the hidden variables.

Get the selected value of a group of HtmlInputRadioButton controls

When using the RadioButtonList control, I can access the selected value in my codebehind with the following:
rbMyButtons.SelectedValue
However, I'd like to use HtmlInputRadioButton controls instead as these give me greater control over the rendered markup. If I'm using a list of <input type="radio" runat="server" /> then, as far as I know, I have to do something like this:
if (rbMyButtonsOption1.Checked)
{
...
}
else if (rbMyButtonsOption2.Checked)
{
...
}
else if ...
Is there a way I can mimic the behaviour of RadioButtonList.SelectedValue without using Request.Form["name"]?
Here's how I would do it:
First, wrap the Html Controls inside a panel or similar grouping object (the panel will be rendered as a div):
<asp:Panel runat="server" ID="ButtonList" ClientIDMode="Static">
<input type="radio" name="seasons" value="Spring" runat="server" />Spring <br/>
<input type="radio" name="seasons" value="Summer" runat="server" /> Summer <br/>
<input type="radio" name="seasons" value="Fall" runat="server" /> Fall <br/>
<input type="radio" name="seasons" value="Winter" runat="server" /> Winter <br/>
</asp:Panel>
Then, create an extension method to access the ControlCollection property of the panel and iterate through the collection:
public static class HelperFunctions
{
public static string GetRadioButtonValue(this ControlCollection collection)
{
foreach (var control in collection)
{
if (control is HtmlInputRadioButton)
{
var radioControl = ((HtmlInputRadioButton)control);
if (radioControl.Checked)
{
return radioControl.Value;
}
}
}
//If no item has been clicked or no Input Radio controls are present we return an empty string
return String.Empty;
}
}
Finally you can get the value with ease:
var selectedValue = ButtonList.Controls.GetRadioButtonValue();
I did some searching to find this, so thought it may be useful even though the question is over 1 year old...
I've just come across this issue. I needed to use use [input type="radio" runat="server" ...] as I had to include additional HTML "data-*" attributes against each selection.
I've used a composite of the two answers here to come with a solution that helped me.
My HTML looks like:
<div id="pnlOpts" runat="server">
<input type="radio" name="rblReason" runat="server" value="1" /> <label>Opt 1</label><br />
<input type="radio" name="rblReason" runat="server" value="3" data-att="1" /> <label>Supplied Reason 1 </label><br />
<input type="radio" name="rblReason" runat="server" value="3" data-att="2" /> <label>Supplied Reason 2 </label><br />
<input type="radio" name="rblReason" runat="server" value="3" data-att="3" /> <label>Supplied Reason 3 </label><br />
</div>
My Code-behind looks like:
if(pnlOpts.Controls.OfType<HtmlInputRadioButton>().Any(a=>a.Checked))
{
HtmlInputRadioButton selected = pnlOpts.Controls.OfType<HtmlInputRadioButton>().Where(a => a.Checked).FirstOrDefault();
var btnValue = selected.Value;
var dataAttVal = selected.Attributes["data-att"];
...
}
You can mimic this behavior using LINQ:
var radioButtons = new[] { rbMyButtonsOption1, rbMyButtonsOption2 };
var checkedRadioButton = radioButtons.FirstOrDefault(i => i.Checked);
if (checkedRadioButton != null)
{
// do something...
}

How to populate html input from server side

I am not quite sure how to attack this, basically I have two html fields in my aspx page:
<input type="text" name="fname" />
<input type="text" name="lname"/>
Now i would like to populate them from the server side when the page loads based on some data collected from the database, basically this data is stored in two properties
public string FirstName { get; set;}
public string LastName {get; set;}
How can I pass the value from such properties into the html inputs On_Load ?
I would appreciate the help.
Here is one way, assuming Webforms:
<input type="text" name="fname" value="<%:FirstName%>" />
<input type="text" name="lname" value="<%:LastName%>" />
If using .NET before 4.0, replace the <%: with <%=.
Another option is to change the input types to be runat="server" and assigning the values directly on the server side.
Alternatively add runat="server" to your elements, then you could do something like
fname.Value = FirstName;
lname.Value = LastName;
The info I was looking for was like this:
protected void Page_Load(object sender, EventArgs e)
{
address.Value = Request.QueryString["lat"];
address1.Value = Request.QueryString["long"];
}
takes values from the URL string and puts them in an HTML input="text"
http://localhost:64375/Map.aspx?lat=detroit&long=windsor
Enter Address A: <input runat="server" name="address" id="address" type="text" />
Enter Address B: <input runat="server" name="address1" id="address1" type="text" />
thanks Ash and Oded for the combined answer

C# ASPX - Form Submission Query

I have a C# aspx form in which I need to input it's data into an SQL database and then return a response saying successful or not. I have no idea how to get the form data that is sent from the Default.aspx page. My basic code structure is below:
Default.aspx
<form runat="server" name="aForm" action="Results.aspx" method="post" onsubmit="ValidateForm()">
<input name="firstname" type="text" />
<input name="surname" type="text" />
<input type="submit" value="Submit" />
</form>
Results.aspx.cs
public partial class AwardsForm : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack){
Response.Redirect("Default.aspx");
} else (this.IsPostBack) {
writeResults(FormSubmit());
}
protected boolean FormSubmit() {
// get form data and insert it into SQL
// return true/false based on success
}
protected void writeResults(boolean results) {
if (results == true) {
Response.Write ("Success");
} else {
Response.Write ("Failed");
}
}
}
You can get the posted form data through Request.Form["key"], or, if your form elements are decorated with runat="server" then you should be able to grab them by id right in your code behind
<asp:TextBox id="yourTb" runat="server"></asp:TextBox>
string postedText = yourTb.Text;
Or you can do (though this is much less common)
<input type="text" runat="server" id="yourOtherTb" />
string otherPostedText = yourOtherTb.Value;
Or if you're working with purely html form inputs:
<input type="text" id="clientTb" name="clientTb" />
string clientText = Request.Form["clientTb"];
You can try by the following code.
string firstname = Request.Form["firstname"]
string surname = Request.Form["surname"]
Since you are doing something like this
<input name="firstname" type="text" />
<input name="surname" type="text" />
<input type="submit" value="Submit" />
the name attribute of the input controls are posted back to the server(IIS). Hence you would do this.
If(IsPostBack)
{
string firstName = Request.Form["firstname"];
string surName = Request.Form["surname"];
if(string.IsNullOrEmpty(firstName))
{
Response.Write("Firstname is required this form");
}
}

Categories