How do I access values from string array in c#? - c#

Can anyone help me please? I'm really stuck.
I need to be able to access the values of the following in the post method (the name and the qty) so that I can add them to the model. (the inputs will be generated by JavaScript
<div id="ingredientsMainContainer">
<input type="text" name="Ingredient[0][Name]" />
<input type="text" name="Ingredient[0][Qty]" />
<input type="text" name="Ingredient[1][Name]" />
<input type="text" name="Ingredient[1][Qty]" />
</div>
The list can be unlimited, so it could go up to Ingredient[10] or more.
I can access like this:
var test = Request.Form["Ingredient[0][Name]"];
var test2 = Request.Form["Ingredient[1][Name]"];
but I need to loop through all Ingredient[] inputs for the Name and Qty.
Thanks

A for-loop and string concatenation should work:
for (int i = 0; i < 2; i++) {
// $"Ingredient[{i}][Name]" is the same as "Ingredient[" + i + "][Name]"
Request.Form[$"Ingredient[{i}][Name]"];
}

Related

Addition and Removal of parts of a Dynamic Form Array

I am currently playing around an idea of making views as much typed as possible. What I want to do is make a Partial View that will be capable of adding a new items into the array/list (and ofc the removal as well). I have noticed that I am basically unable to avoid JavaScript, however I wish not to hardcore anything other than URLs. Is it possible to achive this without making basically unreadable reflection for someone that gets the code in their hands after me ?
For a bit more clarification, lets assume a simple Pizza shop with the following models:
PizzaViewModel:
public class PizzaViewModel
{
[Required]
public string Name { get; set; } = "";
[Required]
public string Description { get; set; } = "";
[Required]
public IList<IngredientViewModel> Ingredients { get; set; } = new List<IngredientViewModel>();
}
IngredientViewModel:
public class IngredientViewModel
{
public int Id { get; set; }
public string? Name { get; set; }
[Required]
public int Amount { get; set; }
[Required]
public string? TypeOfAmount { get; set; }
}
What I want to be able to create is something that resembles something like this:
Form
- Name
- Description
- (Ingredient1 Name; Ingredient1 Amount)
- (Ingredient2 Name; Ingredient2 Amount)
...
- (IngredientX Name; IngredientX Amount)
- [Add Ingredient ; Remove Ingredient]
Now, to the core of my question, is it possible to write the HTML/Csharp method using PartialView or even the view itself to generate something like this?
<div id="NewItem" style="display:none">
<input type="text" name="Ingredient[#_PlaceHolder_#].Name"/>
<input type="text" name="Ingredient[#_PlaceHolder_#].Amount"/>
</div>
to be a little bit more specific:
<input type="text" name="Ingredient[#_PlaceHolder_#].Amount"/>
^ ^
I wish not to hardcore these, since they can be changed while refactoring
Additionally, regarding the removal, I am kinda wondering if its possible to do this differently than just re-indexing the whole array.
Thank you all in advance for any help.
if I understand correctly
It is possible to generate a dynamic form array in ASP.NET Core without hardcoding the index. You can use JavaScript to handle the addition and removal of items in the list, but you can also make use of Razor's support for indexed properties to keep track of the index. Here's a simple example that demonstrates how this can be done:
<form asp-action="Create">
<div class="form-group">
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Description"></label>
<input asp-for="Description" class="form-control" />
</div>
<div id="ingredients">
#for (var i = 0; i < Model.Ingredients.Count; i++)
{
<div class="form-group">
<label asp-for="Ingredients[i].Name"></label>
<input asp-for="Ingredients[i].Name" class="form-control" />
<label asp-for="Ingredients[i].Amount"></label>
<input asp-for="Ingredients[i].Amount" class="form-control" />
</div>
}
</div>
<button id="add-ingredient" type="button">Add Ingredient</button>
<input type="submit" value="Create" class="btn btn-primary" />
</form>
<script>
$(document).ready(function () {
var ingredients = $('#ingredients');
var index = #Model.Ingredients.Count;
$('#add-ingredient').click(function () {
ingredients.append(
'<div class="form-group">' +
'<label for="Ingredients[' + index + '].Name"></label>' +
'<input type="text" asp-for="Ingredients[' + index + '].Name" class="form-control" />' +
'<label for="Ingredients[' + index + '].Amount"></label>' +
'<input type="text" asp-for="Ingredients[' + index + '].Amount" class="form-control" />' +
'</div>'
);
index++;
});
});
</script>
In this example, the index is managed in JavaScript and appended to the name attribute of each input field. The Razor code generates the initial form inputs using a loop, and the JavaScript code adds new inputs when the "Add Ingredient" button is clicked. To remove an item, you can add a button next to each ingredient that removes its corresponding inputs.

ajax only sends the first value of input and not the others?

I made a school website where teachers will be able to upload the students' marks. Up to now I have these three files:
The first one, will display every students name depending on the subject and course
<table class="check">
<tr class="arrow">
<th>Student</th>
<th>Add Mark</th>
</tr>
#foreach(var users in user){
<tr class="arrow">
<td>#users.Nombre #users.Apellido</td>
<td>
<form method="post">
<input type="text" id="user" style="display: none" name="user" #Validation.For("nombre") value="#users.UserId" />
<input type="text" id="galleryId" style="display: none" name="galleryId" #Validation.For("nombre") value="#galleryId" />
<input type="text" id="note" name="button2" name="note" #Validation.For("nombre") />
<input type="button" value="Ready" title="Ready" onclick="loco(document.getElementById('user').value, document.getElementById('galleryId').value, document.getElementById('note').value)" />
</form>
</td>
</tr>
}
</table>
Here you can see that I used foreach to display every student's name, and then next to it there should be displayed an input textbox for the teacher to write the mark of a specific student. That's why I included the form in the foreach.Next is the ajax file:
function loco(user, gallery, note) {
var xmlhttp;
var user = document.getElementById("user").value;
var galleryid = document.getElementById("galleryId").value;
var note = document.getElementById("note").value;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/Marks/add1/" + gallery + "/" + user + "/" + note, true);
xmlhttp.send();
}
And finally, we have the page which will insert the marks to the database without returning any table or div, just uploading the mark.
#{
var db2 = Database.Open("ica");
var user = UrlData[1];
var galleryId = UrlData[0];
var note = UrlData[2].AsInt();
db2.Execute("INSERT INTO Notas (Nota, UserId, Sub_Id) VALUES (#0, #1, #2)", note, user, galleryId);
}
So, why does the ajax send the values of the first student to the upload file and not the second, third, etc? Why, when I click on the submit button of the second student does it sends the mark of the first student again, and only that of the first student?
You're using hard-coded IDs in the HTML inside your for-each loop, so you're going to get multiple elements on your page with the same IDs for user, galleryId and note. That means that your selector can only select the first no matter which you're actually trying to use. You need to do something such as adding an index number to the end of the ID instead of fully hard-coded IDs, so that they can be distinguished from one another.
NOTE:
I observed you using name multiple times in same input please remove that:
<input type="text" id="note" name="button2" name="note" #Validation.For("nombre") />
here you gave name as button2 as well note please remove button2
Make the changes as below:
function loco(form) {
var xmlhttp;
var user = form.name.value;
var gallery = form.galleryId.value;
var note = form.note.value;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/Marks/add1/" + gallery + "/" + user + "/" + note, true);
xmlhttp.send();
return false;
}
change your html related code as below:
<form onsubmit="return loco(this)">
<input type="text" id="user" style="display: none" name="user" #Validation.For("nombre") value="#users.UserId" />
<input type="text" id="galleryId" style="display: none" name="galleryId" #Validation.For("nombre") value="#galleryId" />
<input type="text" id="note" name="note" #Validation.For("nombre") />
<input type="submit" value="Ready" title="Ready" />
</form>

Make request[] to auto generated list item

I was wondering, how would I go about making a request to a auto generated list of <input type="checkbox">.
The code I have so far is this:
#{
if(Request["btn"] == "update")
{
// make a list with the checked items
}
}
<div>
<form action="" method="post">
#{
string tempChecked = "";
foreach(Roles r in Roles.getAll(con))
{
if(Users.doesUserHaveRole(con,r.name,user._id))
{
tempChecked = "checked";
}
<input type="checkbox" name="#r._id" #tempChecked >#r.name
<br />
tempChecked = "";
}
}
<input type="submit" value="update" name="btn" />
</form>
</div>
How would I go about doing this, when I can't make a Request["whatever number it has"]?
You are close use
Request.Form[list name].ToString()
This will give you a list of checked check boxes. Something like 1,2,5, etc. Hopefully this helps
Edit:
I believe this comes back as null if nothing has been checked. You can put the result into an array using the split function. something like this
try{
foreach(var temp in Request.Form[List Name].ToString().Split(',')){
//this will then iterate over every check box that has been checked and you can save to the database or do something else with them.
}
}catch{
//No items were checked
}

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

Get posted value In C# ASP.NET

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.

Categories