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

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>

Related

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

How to find the form in scrapysharp when it only has attributes i.e. no name or id

I am new to scrapySharp as well as web scraping. I am trying to scrape a site that is secured and has a login screen. The form element does not have a name/id attribute, thus making my life more complicated. I have been unable to figure out how to load the form using the code below. Any insight is greatly appreciated!
C#:
ScrapingBrowser browser = new ScrapingBrowser();
var homepage = browser.NavigateToPage(new Uri("https://somedomain.com/ProviderLogin.action/"));
var form1 = homepage.Find("form", ScrapySharp.Html.By.Text("form"));
var form2 = homepage.FindFormById("form[action='provider-login']");
HTML:
<form action="provider-login" method="post">
<div class="login-box">
<input type="text" name="username" id="username" autocomplete="false" placeholder="Username"
class="form-control input-lg login-input login-input-username" value="" />
<input type="password" id="password" name="password" placeholder="Password" type="password"
class="form-control input-lg login-input login-input-password" />
<button name="login" type="submit" class="btn btn-primary btn-block btn-md login-btn" >
Login
</button>
</div>
</form>
You can't achieve that using in ScrapySharp using the "By" since it has just four "Element Search Kinds" :
{
Text,
Id,
Name,
Class
}
In your case, you don't have one of them so consider to use "CssSelect" instead to achieve your purpose :
var form = homepage.Html.CssSelect("form[action='provider-login']");
//Or
var form = homepage.Html.CssSelect("form[action*='provider-login']");
You can find the first form node by tag, then use the PageWebForm constructor:
var browser = new ScrapingBrowser();
var homepage = browser.NavigateToPage(new Uri("https://somedomain.com/ProviderLogin.action/"));
var form1node = homepage.Html.SelectSingleNode("//form");
var form1 = new PageWebForm(form1node, browser); // this is where it happens!
form1["username"] = "some username";
form1["password"] = "some password";
form1.Method = HttpVerb.Post;
var webpage = form1.Submit();

Asp.net MVC - form is not sent to controller

In a Asp.net MVC view, i created a form, with a input field.
The user Sets a first name (or part of it), presses the submit button.
This is the form section:
<div>
<form action="SearchCustomer" methos="post">
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
</form>
</div>
This is the SearchCustomer in the Controller, that gets the data from the form:
CustomerDal dal = new CustomerDal();
string searchValue = Request.Form["txtFirstName"].ToString();
List<Customer> customers = (from x in dal.Customers
where x.FirstName.Contains(searchValue)
select x).ToList<Customer>();
CustomerModelView customerModelView = new CustomerModelView();
customerModelView.Customers = customers;
return View("ShowSearch", customerModelView);
When i run the program, and enter a first name ("Jhon" for example), the code returns to SearchCustomer function, but Request.Form is empty.
Why?
Thanks.
Your method is spelled wrongly should not read methos but method like below:
<form action="SearchCustomer" method="post">
....
</form>
You need to modify your code:
you need to provide a action name here, which should be defined in your controller(SearchController) with the same name as 'ActionName' you will put in the below code.
if SearchController is your action name then provide the controller in which the action is available.
<div>
<form action="SearchCustomer/<ActionName>" method="post">
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
</form>
</div>
With Html.BeginForm :
#using (Html.BeginForm("<ActionName>","<ControllerName>", FormMethod.Post))
{
Enter first name: <input id="Text1" name="txtFirstName" type="text" />
<br />
<input id="Submit1" type="submit" value="Search Customer" />
}
Set [HttpPost] on your controller.
[HttpPost]
public ActionResult SearchFunction(string txtFirstName)
{
CustomerDal dal = new CustomerDal();
string searchValue = txtFirstName;
List<Customer> customers = (from x in dal.Customers
where x.FirstName.Contains(searchValue)
select x).ToList<Customer>();
CustomerModelView customerModelView = new CustomerModelView();
customerModelView.Customers = customers;
return View("ShowSearch", customerModelView);
}
If you View is the same name as your ActionResult method, try this:
#using(Html.BeginForm())
{
... enter code
}
By default, it'll already be a POST method type and it'll be directed to the ActionResult. One thing to make sure of: You will need the [HttpPost] attribute on your ActionResult method so the form knows where to go:
[HttpPost]
public ActionResult SearchCustomer (FormCollection form)
{
// Pull from the form collection
string searchCriteria = Convert.ToString(form["txtFirstName"]);
// Or pull directly from the HttpRequest
string searchCriteria = Convert.ToString(Request["txtFirstName"]);
.. continue code
}
I hope this helps!

Trying to do a very basic login page using CSHTML but I can't get my if statement to work correctly

#{
Page.Title = "Log in";
// Generate page variables
var db = Database.Open("calcinema");
var email = "";
var password = "";
var getAcc = db.Query("SELECT * FROM Account;");
if (IsPost && Validation.IsValid()) {
email = #Request.Form["email"];
password = #Request.Form["password"];}
foreach (var a in getAcc) {
if (email == a.Email && password == a.Password){
Response.Redirect("~/Browse.cshtml");}
}
}
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table border="0" align="center">
<tr>
<td>
<form name="login" action="" method="get" accept-charset="utf-8">
<label for="email">Email</label>
<input type="email" name="email" placeholder="yourname#email.com" required value = "#Request.Form["email"]">
<label for="password">Password</label>
<input type="password" name="password" placeholder="Password" required value = "#Request.Form["password"]">
<input type="submit" value="Login">
</form>
</td>
</tr>
</table>
</body>
The page loads but nothing happens regardless of whether or not the email and password is valid. It just takes the input and then returns me to the login page with the text fields empty as opposed to redirecting me to the Browse.cshtml page.
The issue is your form's method. You have chosen GET which passes the form values in the QueryString. You are looking in the Request.Form collection, but the values aren't there. Change the method to POST.
You also need to make sure you query the database properly and return the result to be examined by your code. There are also other issue in that you cannot set the value of an input type=password and the required attribute does not work with server-side validation.
Here's some code that will work, but I recommend you spend some time with the tutorials here and learn the basics of Web Pages. It's a great framework but does require a bit of application to learn properly.
#{
Page.Title = "Log in";
if (IsPost && Validation.IsValid()) {
var email = Request.Form["email"];
var password = Request.Form["password"];
var db = Database.Open("calcinema");
var result = db.QueryValue("SELECT Count(*) FROM Account WHERE Email = #0 AND Password = #1", email, password);
if (result > 0){
Response.Redirect("~/Browse.cshtml");
}
}
}
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table border="0" align="center">
<tr>
<td>
<form name="login" action="" method="post" accept-charset="utf-8">
<label for="email">Email</label>
<input type="email" name="email" placeholder="yourname#email.com" required value = "#Request.Form["email"]">
<label for="password">Password</label>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Login">
</form>
</td>
</tr>
</table>
</body>
Your issue is likely this:
email = #Request.Form["email"];
password = #Request.Form["password"];
You don't need to prefix Request with an ampersand since you're already in server-side code:
email = Request.Form["email"];
password = Request.Form["password"];
You really shouldn't be doing this. You should pass those values as parameters to your SQL command then see if there is a match:
var result = db.QueryValue("SELECT COUNT(*) FROM Account WHERE email = #0 AND password = #1", email, password);
And of course, the various security considerations about SSL, plain-text password and SQL injection safeguards apply.
It is because of the if clause statement that you're providing. The statement would never be true with this HTML form's method. You nee to change it.
Have a look
if (IsPost && Validation.IsValid()) {
email = #Request.Form["email"];
password = #Request.Form["password"];
}
foreach (var a in getAcc) {
if (email == a.Email && password == a.Password) {
Response.Redirect("~/Browse.cshtml");
}
}
You need to execute the #Request.Form["email"] code only if the request if POST, but your form is set to method="get" which would always skip the IF block.
And since the if block is skipped, your code would always have a value of empty string or the initial value that the email and password both had. Thus, the second if block would also not execute and won't redirect you to the Browse.cshtml page.

Generating a POST request for PayPal button in C# ASP.net

I'm trying to allow a web form to use a PayPal buy it now.
The relevant page is here.
Based on which radio button a user selects, depends on which paypal button they are "redirected" to.
The subscriptions are easy - they are just a simple redirect.
The last option, requires a user select a venue.
For this, i require to use the form below:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="10956105">
<table>
<tr><td><input type="hidden" name="on0" value="Venue">Venue</td></tr><tr><td>
<input type="text" name="os0" maxlength="60"></td></tr>
</table>
<input type="image" src="https://www.paypal.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypal.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
But of course, I want to do it without using that form.
What I have so far is:
if (singleOneOff.Checked)
{
paypalForm.Text = getPaypalForm(venueSelect.SelectedItem.Text);
var strJS = getPayPalPostJS("_xclick");
paypalJs.Text = strJS;
var xxx = "dd";
}
This determines if that particular radio button was ticked.
getPaypalForm
private String getPaypalForm(string venue)
{
StringBuilder strForm = new StringBuilder();
strForm.Append(#"<form action=""https://www.paypal.com/cgi-bin/webscr"" name=""_xclick"" method=""post"">");
strForm.Append(#"<input type=""hidden"" name=""cmd"" value=""_s-xclick"">");
strForm.Append(#"<input type=""hidden"" name=""hosted_button_id"" value=""10956105"">");
strForm.Append(#"<input type=""hidden"" name=""on0"" value=""Venue"">");
strForm.Append(#"<input type=""text"" name=""os0"" value=""{0}"" maxlength=""60"">");
strForm.Append("</form>");
return String.Format(strForm.ToString(), venue);
}
getPayPalPostJS
private String getPayPalPostJS(string strFormId)
{
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var paypalForm = document.forms.namedItem('{0}');");
strScript.Append("paypalForm.submit();");
strScript.Append("</script>");
return String.Format(strScript.ToString(), strFormId);
}
However, if i select the radio button, and a venue, and press the button, nothing happens....
Any ideas where i've gone wrong?
I followed this guide: http://www.netomatix.com/development/postrequestform.aspx
Here's a much cleaner, server-side solution to the ASP.NET/PayPal single form problem:
http://codersbarn.com/post/2008/03/08/Solution-to-ASPNET-Form-PayPal-Problem.aspx
The root of the problem is that ASP.Net web forms wrap everything on the page inside of one large <form> tag. Your paypal code is rendering a nested form and that doesn't work.
Read this question for more information.

Categories