Get values from multiple inputs with the same name. c# .net - c#

I have this html form:
<form method="post" action="/Record">
<input type="text" name="items[0][name]" value="Watch" />
<input type="text" name="items[0][model]" value="Ballon" />
<input type="text" name="items[1][name]" value="Shape" />
<input type="text" name="items[1][model]" value="Bleu" />
<input type="text" name="items[2][name]" value="Accessory" />
<input type="text" name="items[2][model]" value="Hublot" />
<input type="submit" value="SEND" />
</form>
I need to get the value of every item. i try something like this in c# .net
String[] myItems;
myItems = Request.Form.GetValues("items");
foreach (var singleItem in myItems)
{
WriteLine(singleItem.name);
WriteLine(singleItem.model);
WriteLine(singleItem["name"]);
WriteLine(singleItem["model"]);
}
i appreciate your advice

let try as below:
var myItems = Request.Form["items"];

Related

Can you have 2 buttons in a form, when using Unobtrusive AJAX in Razor Pages?

I have 2 OnPost handlers in the PageModel for a form, is there a way to run Unobtrusive AJAX with different post handlers on each button? I can't seem to find anything on this. Or is there a better way of achieving this through JQuery?
Both handlers seem to be doing the correct function, but I can only run one or the other currently using this method.
Here is what I have:
<form method="post" data-ajax="true" data-ajax-method="post" data-ajax-update="#panel">
<input type="hidden" value="#Model.Options.Count()" name="optionCount" />
<input type="hidden" value="#Model.Product.Name" name="product" />
<input type="hidden" value="#Model.Product.ProductId" name="productId" />
<input type="hidden" value="#Model.Headings" name="headings" />
<input type="hidden" value="#Model.HeadingsString" name="headingsString" />
<input type="hidden" value="#Model.Price" name="price" />
#foreach (var item in Model.Headings.Select((value, index) => new { value, index }))
{
<div class="form-group">
<label class="control-label" id="headingA">#item.value</label>
#foreach (var option in Model.Options.Select((value, index) => new { value, index }))
{
if (item.index == option.index)
{
<select class="form-control" name="#item.index" asp-items="option.value"></select>
}
}
</div>
}
<p>
<strong>Price:</strong>
<div id="panel">#Model.Price</div>
</p>
<button type="submit" class="btn btn-outline-primary">Calculate</button>
<button class="btn btn-outline-primary" asp-page-handler="Cart">Add To Cart</button>
</form>
Thanks for any info!
This is a hack, but seems to be working.
I only needed 1 AJAX post handler in my case, so I edited data-ajax="true/false", with JQuery button click event, which enabled the button (not needing AJAX) to post with its handler.
<form method="post" id="form" data-ajax-method="post" data-ajax-update="#panel">
<input type="hidden" value="#Model.Options.Count()" name="optionCount" />
<input type="hidden" value="#Model.Product.Name" name="product" />
<input type="hidden" value="#Model.Product.ProductId" name="productId" />
<input type="hidden" value="#Model.Headings" name="headings" />
<input type="hidden" value="#Model.HeadingsString" name="headingsString" />
<input type="hidden" value="#Model.Price" name="price" />
#foreach (var item in Model.Headings.Select((value, index) => new { value, index }))
{
<div class="form-group">
<label class="control-label" id="headingA">#item.value</label>
#foreach (var option in Model.Options.Select((value, index) => new { value, index }))
{
if (item.index == option.index)
{
<select class="form-control" name="#item.index" asp-items="option.value"></select>
}
}
</div>
}
<p>
<strong>Price:</strong>
<div id="panel">
<label id="price">#Model.Price</label>
</div>
</p>
<button id="buttonAdd" type="submit" class="btn btn-outline-primary">Calculate</button>
<button id="buttonRemove" class="btn btn-outline-primary" asp-page-handler="Cart">Add To Cart</button>
</form>
The JQuery
<script>
$(document).ready(function () {
$("#buttonAdd").click(function () {
$("#form").attr("data-ajax", "true");
});
});
$(document).ready(function () {
$("#buttonRemove").click(function () {
$("#form").attr("data-ajax", "false");
});
});

ASP.Net Core MVC Disable validation when a specific button is pressed

I have 2 buttons on my form, a Submit and Save button. I want to be able to skip all validation when a user clicks the Save button. I've tried adding class="cancel", formnovalidate, formnovalidate="formnovalidate", disableValidation="true" to the Save button but none of them worked. Any help would be wonderful! I'm using ASP.NET Core 3.1.
Form
<form asp-action="Request">
...
...
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" class="btn btn-secondary" />
</form>
<partial name="_ValidationScriptsPartial" />
Firstly,you need to know,if you use _ValidationScriptsPartial,it would generate the html like below:
Generate cshtml from:
<input asp-for="MyDate" class="form-control" />
to:
<input class="form-control" type="date" data-val="true"
data-val-required="The MyDate field is required."
id="MyDate" name="MyDate" value="">
formnovalidate and class="cancel" attribute could skip the validation in client side,but could not skip validation in server side.
To fix such issue,you could clear model state:
1.Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(add formnovalidate to save input):
#model Test
<form asp-action="Request">
<div>
Name:<input asp-for="Name" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div>
Id:<input asp-for="Id" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" formnovalidate class="btn btn-secondary" />
</form>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
3.Action:
[HttpPost]
public IActionResult Request(Test test)
{
if (!ModelState.IsValid)
{
ModelState.Clear();
return View("Index");
}
return View("Index");
}
4.Result:
<form asp-action="Request">
...
...
<input name="answer" type="submit" value="Submit" class="btn btn-primary" />
<input name="answer" type="submit" value="Save" class="btn btn-secondary cancel" />
</form>
#section Scripts{
<partial name="_ValidationScriptsPartial" />
}

How to access array of fields from a form in ASP.NET?

Please forgive me if this question is a duplicate, because I could not find the answer to this question anywhere else on Stack Overflow.
I have a form in ASP.NET that has multiple fields, and more fields can be added through jQuery. In my form, I want an array of friends.
This is the friend class:
public class Friend {
public string Name { get; set; }
public int Age { get; set; }
}
This is my form, and users can add as many friends as they want, by clicking a button that adds a row with these two fields. For example:
<table>
<tr>
<input type="text" name="friend[0].Name" />
<input type="text" name="friend[0].Age" />
</tr>
<tr>
<input type="text" name="friend[1].Name" />
<input type="text" name="friend[1].Age" />
</tr>
<tr>
<input type="text" name="friend[2].Name" />
<input type="text" name="friend[2].Age" />
</tr>
...
</table>
How would I access these as a list of friends, in my function in the controller?
I Think you're almost there,
<form method="post" action="/Home/UpdateFriends">
<input type="text" name="[0].Name" value="Curious George" />
<input type="text" name="[0].Age" value="20" />
<input type="text" name="[1].Name" value="Code Complete" />
<input type="text" name="[1].Age" value="50" />
<input type="submit" />
</form>
controller should look like this
//Action method on HomeController
public ActionResult UpdateFriends(ICollection<Friend> friends) {
//your code here
}
this article explains it more in depth.

Jquery Validation for a single field

My form is
#using (Html.BeginForm("Create", "Account", FormMethod.Post, new { #class = "CreateUser" ,id="createform"}))
{
#Html.ValidationSummary();
<div class="field"><label>User Name*</label></div><input name="UserName" type="text" />
<div class="field"><label>Name</label></div><div class="field1"><input name="FirstName" type="text" placeholder="First Name"/><input name="Middlename" type="text" placeholder="Middle Name" /><input name="LastName" type="text" placeholder="Last Name" /></div>
<div class="field"><label>Email*</label></div><input name="Email" type="text" />
<div class="field"><label>Mobile*</label></div><div class="field2"><input name="CountryCode" type="text" placeholder="Country Code" /><input name="Mobile" type="text" placeholder="Mobile Number" /></div>
<div class="field"><label>Language</label></div><input name="Language" type="text" />
<div class="field"><label>Expiry Date*</label></div><input name="Expiry" type="text" id="datepicker" />
<input id="send" class="subbtn" type="submit" value="Create"/>
How can I validate only user name field using jQuery?
if your need required field validator, you can use something like this(JS):
<input name="UserName" type="text" id="UN"/>
var textBox = document.getElementById('UN');
if(textBox=='')
//your error message
It looks like you want make user name a mandatory field. If it is so you need to add following attribute to your user name input control:
<input name="UserName" type="text" data-val="true" data-val-required="User name field is required."/>
Also you need to configure unobtrusive validation here is the link how to do it: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
$(document).ready(function(){
$('#createform').submit(function(){
var user_name = $('input:first').val();
if(user_name == /*whatever you want to test*/){
//doesn't pass test
this.preventDefault();
alert("Username error");
} else {
this.submit();
}
});
});

Parsing Form action and input name and values using html agility pack

I'm trying to parse the form action value and input name with value from the following HTML code:
<form method="post" action="actionURL" autocomplete="" name="login_form" id="login_form" onsubmit="return hash2(this)">
<input type="hidden" name=".tries" value="1">
<input type="hidden" name=".src" value="ym">
<input type="hidden" name=".md5" value="">
<input type="hidden" name=".hash" value="">
<input type="hidden" name=".js" value="">
<input type="hidden" name=".last" value="">
<input type="hidden" name="promo" value="">
<input type="hidden" name=".intl" value="us">
<input type="hidden" name=".lang" value="en">
<input type="hidden" name=".bypass" value="">
<input type="hidden" name=".partner" value="">
<input type="hidden" name=".u" value="8013sg1858dp9">
<input type="hidden" name=".v" value="0">
<input type="hidden" name=".challenge" value="fUhehaaMq9c2lQjndCps_rNu1eSB">
<input type="hidden" name=".yplus" value="">
<input type="hidden" name=".emailCode" value="">
<input type="hidden" name="pkg" value="">
<input type="hidden" name="stepid" value="">
<input type="hidden" name=".ev" value="">
<input type="hidden" name="hasMsgr" value="0">
<input type="hidden" name=".chkP" value="Y">
<input type="hidden" name=".done" value="somevalue">
<input type="hidden" name=".pd" value="ym_ver=0&c=&ivt=&sg=">
<input type="hidden" name=".ws" id=".ws" value="0">
<input type="hidden" name=".cp" id=".cp" value="0">
<input type="hidden" name="nr" value="0">
<input type="hidden" name="pad" id="pad" value="5">
<input type="hidden" name="aad" id="aad" value="5">
<div id='inputs'>
<label for='username'>Yahoo! ID</label>
<input name='login' id='username' maxlength='96' tabindex='1' value=''>
<p id='ex'>(e.g. test)</p>
<label for='passwd'>Password</label>
<input name='passwd' id='passwd' type='password' maxlength='64' tabindex='2'>
<div id="captchaDiv"></div>
</div>
<div id='fun'></div>
<div id='persistency'>
<input type='checkbox' name='.persistent' id='persistent' tabindex='4' value='y' >
<p>
<label for='persistent'>Keep me signed in</label>
<br>
<span id='uncheck'>(Uncheck if on a shared computer)</span>
</p>
</div>
<div id='submit'>
<button type='submit' id='.save' name='.save' class='secondaryCta' tabindex='5'>
Sign In
</button> </div>
</form>
The above form contains, input type in direct children and beside children of children. While using sample here: https://stackoverflow.com/a/9890022/1007447 code trace on c# finds no elements or Descendants for name "form".
How to get the form action and all input types with value? (sometimes, I need to skip the username password part too)
This has been discussed a few times here on Stack Overflow.
The answer is in the same question you are referring to. You have to do:
HtmlNode.ElementsFlags.Remove("form");
var doc = ... //Load the document here
var nodes = doc.DocumentNode.SelectNodes("//form//input");
The key is on the line
HtmlNode.ElementsFlags.Remove("form")
and the explanation of why you need to add it can be found at the following pages:
No child nodes for FORM objects
How to get all input elements in a form with HtmlAgilityPack

Categories

Resources