Make request[] to auto generated list item - c#

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
}

Related

asp.net razor pages: binding checkbox result to dataset

I am completely new to a project I am to maintain.
Simply question: I have in my cshtml page (which I understand are razor pages?) set up a few checkboxes and a label to test the bound class behind it.
This I got to work:
#model Application.Areas.Cms.Models.ProduktBeispielViewModel
<label>#Model.Test</label>
And the VM:
public string Test { get; set; } = "THIS IS A TEST";
And happy me: the words are displayed on my page. So the binding is working.
Now I put up a few checkboxes and once a submit button is pressed, I need to retrieve each checkbox and see if their value is checked or unchecked (shouldnt be too hard).
I first now just tried to display a value (eg true or false) from my VW onto my existing checkboxes.
This is what I did:
public bool Test2 { get; set; } = true;
CSHTML:
<input type="checkbox" name="FoodTrends" value="#Model.Test2" />
I am seeing my checkbox, but it is unchecked.
1.) Why is my simple binding not working? is "value" not the right property?
2.) How would I retrieve my value from this checkbox
Thank you all!
Please have a look at this:
I am returning my model, with the value on Test2 being false
Now this is my exact code in my view:
<input type="checkbox" name="FoodTrends" value="#Model.Test2" checked="#Model.Test2" />
And the result is that the checkbox is checked, even though the value is set to false.
I have noticed also that my checkboxes are inside "<form>" tag.
EDIT:
Razorcode (briefly):
#model Application.Areas.Cms.Models.ProduktBeispielViewModel
#{
ViewBag.PopupHeadline = "Produktbeispiele";
ViewBag.PopupSubHeadline = Model.Item != null ? Model.Item.NameInCurrentLang : "";
ViewBag.HideLanguageComparison = true;
}
#section TabMenu
{
<ul>
<li>Einstellungen</li>
<li>Bild</li>
</ul>
}
<form action="#Url.Action("SaveIndex")" method="POST" id="idForm">
#Html.HiddenFor(m => m.AutoCloseWindow)
#Html.HiddenFor(m => m.Item.Id)
<input type="checkbox" name="FoodTrends" value="#Model.Test2" />
</form>
The checkbox wouldn't work that way you have to use the checked attribute to get selected your checkbox.
#model Practice_web.Models.TestModel
#{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about building Web apps with ASP.NET Core.</p>
</div>
<div>
<input type="checkbox" name="FoodTrends" value="#Model.Test2" checked="#Model.Test2" />
</div>
Action Controller
public IActionResult Index()
{
var model = new TestModel { Test2 = true };
return View(model);
}
Here is the demo video link
Demo Link
Please try this. This works for me like a charm
I don't know if this is a bug or I just don't understand how razor pages work but I have to new up the model first in the AddModel method then it seems to pick up the default value I set in the POCO for my checkbox bool property.
[BindProperty]
public NewMember? User { get; set; }
public AddModel()
{
User = new NewMember();
}

How to let a button disappear after an action and reappear after another action

i have a code that can allow a button to be visible if some values have been saved to a database or in this case has been bookmarked and becomes visible in the front end if it has been deleted from the database.ie has not been bookmarked
verseModel.Verses = verses;
var bookmarksForCurrentChapter = _context.Bookmarks.Where(x => x.ChapterId == id).ToList();
foreach (var verse in verses)
{
foreach (Bookmark bookmark in bookmarksForCurrentChapter)
{
if (bookmark.VerseId == verse.VerseId)
{
verse.IsBookmarked = true;
}
}
}
This is the code to check for if the values have been bookmarked or saved in the database
#if (!verse.IsBookmarked)
{
<td>
<form asp-action="SaveBookmark" method="post">
<input type="hidden" name="id" value="#verse.VerseId" />
<input type="hidden" name="text" value="#verse.VerseText" />
<input type="hidden" name="chapterid" value="#Model.ChapterId" />
<button class="btn btn-outline-primary btn-sm">Save</button>
</form>
</td>
this is the frontend section that makes the button visible when the values are not bookmarked or saved in the database.
So my question is that i want to be add a delete button to this page so that if the value is bookmarked or saved in the database it becomes visible while the save button disappears and if the value has been deleted from the database from this page or from the database directly the delete button will disappear whiles the save button will reappear
else
{
<td>
<form asp-action = "DeleteBookmark" >
<input type = "hidden" name= "id" value = "#verse.VerseId"/>
<button class = "btn btn-danger btn-sm">Delete</button>
</form>
</td>
}
this is what i attempted to do but the button does not work when clicked and if the values are deleted from the database it does not affect the page at all

List hidden value passes wrong value to controller

I have a list In my view. For each row, I view button and I am passing Id value as hidden. But when I click any button it is passing wrong hidden value to the controller. Always it passes the first-row hidden value to the controller.
View:
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</div>
</div>
}
Controller:
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string viewId)
{
return RedirectToAction("ViewDetails");
}
To get all values you need to change the input value type in your controller to array of strings.
I hope that this solution can help you
[HttpPost]
[MultipleButton(Name = "action", Argument = "view")]
public ActionResult ViewDetail(string[] viewId)
{
return RedirectToAction("ViewDetails");
}
if you want to get the exact value you need to duplicate the form within your foreach
in this case you should write somthing like this :
#foreach (var list in Model)
{
<div>
<div > #( ((int)1) + #Model.IndexOf(list)).</div>
<div >#list.details</div>
<div class="col-md-2 row-index">
<form ... > // complete your form attributes
<button class="btn btn-link" type="submit" name="action:view" id="view">View</button>
<input type="hidden" name="viewId" id="viewId" value="list.WId" />
</form>
</div>
</div>
}
Note : You should delete the global form
You should have one form for each row. then you submit that row.
Otherwise as you state it passes first value.
You are setting each value to the same element ID (which is invalid anyway) and name. When you submit your form (which would be more helpful to fully answer your question) it is finding the first element that matches that criteria and submitting it.
There are multiple ways to resolve this such as the already mentioned form per entry but the other preference would be to modify you button to a div and add a click handler to pass the specific value to a js function which would then submit to the controller. Its a preference choice regarding how tightly coupled you want your front end. But the main problem is your element naming convention.

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>

My formulary is not working .... asp.net mvc 4 razor syntax

I already tried a lot of changes and nothing worked.... I am having compiler errors...
The object of the formularys is that the user will give the place a rating using radio button and will write a text review inside TextArea....
#using (Html.BeginForm()) {
Rating:
for(int i=1;i<6;i++){
<text>#i</text>
Html.RadioButton("Rating",i)
}
<h2>Write a Review for #Model.Name</h2>
Html.TextArea("Review")
<input type="submit" value="Send Review" />
}
The issue has to do with how you're trying to print html inside the #using block. Try this:
#using (Html.BeginForm()) {
#:Rating:
for(int i=1;i<6;i++) {
<text>#i</text>
#Html.RadioButton("Rating",i)
}
<h2>Write a Review for #Model.Name</h2>
#Html.TextArea("Review")
<input type="submit" value="Send Review" />
}
Or better yet, replace #:Rating: with
#Html.Label("Rating", "Rating:")

Categories