i have some problem here with Edit Data Using ASP.NET Razor in WebMatrix
i write this code for edit a data using the Update command but unfortunately it doesnt work :s :s
Razor code :
#{
{
var userId = Request["UserId"];
var db = Database.Open("intranet");
var query = "UPDATE Personne SET Demande = #0 WHERE UserId LIKE '%#1%'";
db.Execute(query,"refuser", userId);
}
}
the html code :
<form action="responsable.cshtml" method="post">
<input type="hidden" name="UserId" value="saadwafqui" />
<input type="submit" value="Oui" />
</form>
Your code is vulnerable to SQL injection. I would recommend you fixing this. Also you seem to be using some IsPost variable which is not quite clear where is being defined.
Example:
#{
var userId = Request["userid"];
var db = Database.Open("intranet");
var query = "UPDATE Personne SET Demande = #0 WHERE UserId LIKE '%' + #1 + '%'";
db.Execute(query, "refuser", userId);
}
Notice the syntax around the LIKE clause:
LIKE '%' + #1 + '%'
This will match all records that have UserId in the middle. If you wanted to match only records that the UserId starts with the value in the request:
LIKE '%' + #1
and if you wanted exact match simply use the = operator instead of a LIKE clause.
Also your markup looks completely broken. There's no window.location attribute. Maybe you meant something like this:
<form action="responsable.cshtml" method="post">
<input type="hidden" name="userid" value="saadwafqui" />
<input type="submit" value="Oui" />
</form>
or with a GET request if you prefer:
<form action="responsable.cshtml" method="get">
<input type="hidden" name="userid" value="saadwafqui" />
<input type="submit" value="Oui" />
</form>
Related
I am trying to get a value from a hidden input text box to another page, but it doesn't work. How to pass variable from hidden input box to another page?
Page1.asp
<input type="hidden" name="FormID" value="<% objRS("Form_id")%>
...
<input type="hidden" name="FormID" value="<%= nFormID %>">
<input type="button" value="Open Page2" onclick=openwin();"/>
Page2.asp
<%
iFormID = Request.Form("FormID")
sSQL = "select * from Form where Form_id = " & iFormID
When I click on the Button Open Page2, it doesn't get the value of FormID.
How do I fix it to get the FormID from Page1.asp?
Updated: when I tried to add a button with this JS, it won't get the variable from Page1.asp
I added this on page1.asp:
function openwin()
{window.open("Page2.asp","mywindow","width=500,height=400"):}
<input type="hidden" name="FormID" value="<%= nFormID %>">
<input type="button" value="Open Page2" onclick=openwin();"/>
Thanks.
Since it seems like you're trying to open up a pop up window, I've added a second answer, as you are not actually POSTing any data. if you want to use a pop up, the easiest way is to put the data in the query string, like so:
function openwin()
{window.open("Page2.asp?formID=" + document.frmReport.FormID.value, "mywindow","width=500,height=400"):}
now, i notice you're using a loop to generate the formIDs and using the same NAME for each field. so you'll need to loop through the set of fields, grab each ones value, and send it along as one string in the query string:
function openwin() {
var ids = '';
for( var index = 0; index < document.frmReport.FormID.length; index++ ) {
if( ids == '' )
ids += document.frmReport.FormID[ index ].value;
else
ids += ',' + document.frmReport.FormID[ index ].value;
}
window.open("Page2.asp?FormIDs=" + ids,"mywindow","width=500,height=400");
}
and on Page2.asp, you would do:
iFormIDs = Request.QueryString("FormIDs")
sSQL = "select * from Form where Form_id in ( " & iFormIDs & " ) "
You'll notice that I changed the sql to use the IN clause, that way you can get ALL records for a given set of formIDs, even if it's just one. This obviously doesn't take into account any security precautions to prevent sql injection, but this should get you started.
first, make sure your elements are in a form block with a METHOD of POST
second, your element
<input type="hidden" name="FormID" value="<% objRS("Form_id")%>
needs to be
<input type="hidden" name="FormID" value="<%= objRS("Form_id")%>" />
<%= is shorthand for Response.Write
so page1 would look like:
<form name="myForm" method="post" action="page2.asp">
<input type="hidden" name="FormID" value="<%= objRS("Form_id")%>" />
...
<input type="hidden" name="FormID" value="<%= nFormID %>">
<input type="submit" value="Open Page2" />
</form>
i am using text box to update User record, it Submits half name to database e.g. if Name is 'John Mathew' then it only submits 'John'. EVen i checked in deugging that value being sent from Textbox to action is complete but submitted half, why ? i noticed, my textbox is binded to EmplName field in database and it picks half name from there, in value it shows half name that's why it submit half name why ?
this line :
Controller:
public ActionResult InsertEmployeeEditedDetail(String EmpName, String DeptID, String ShiftId, String EntryDate, String Salary, String Email, bool Approval)
{
int? EmplId = Convert.ToInt32(Session["EmpEdit"]);
var UpdateRec = DataContext.UpdateEmployeeDetails_Sp(EmplId, EmpName, DeptID, ShiftId, EntryDate, Salary, Email, Approval);
return View();
}
View:
#using EmployeeAttendance_app.Models
#model IEnumerable<GetEmployeeEditDetails_SpResult>
#{
var Item = Model.FirstOrDefault();
}
<style type="text/css">
</style>
<div>
#using (Html.BeginForm("InsertEmployeeEditedDetail", "Home", FormMethod.Post))
{
<label id="lblName" class="editEmp_label">Name</label>
<input type="text" value= #Item.EmplName name="EmpName" placeholder="Update Name" />
<br />
<label id="lblDept" class="editEmp_label">Department</label>
#Html.DropDownList("DeptID", #Item.DeptName)
<br />
<label id="lblShift" class="editEmp_label">Shift</label>
#Html.DropDownList("ShiftId", #Item.ShiftName)
<br />
<label id="lblEntryDate" class="TxtBoxFrom editEmp_label">Entry Date</label>
<input type="text" value= #Item.EntryDate class="TxtBoxTo" name="EntryDate" placeholder="Update Date" />
<br />
<label id="lblSalary" class="editEmp_label">Salary</label>
<input type="text" value= #Item.BasicSalary name="Salary" placeholder="Update Salary" />
<br />
<label id="lblEmail" class="editEmp_label">Email</label>
<input type="text" value= #Item.EmailAdd name="Email" placeholder="Update Email" />
<br />
<label id="lblApproved" class="editEmp_label">Overtime Approval</label>
#Html.CheckBox("Approval", #Convert.ToBoolean( #Item.OvertimeApproved))
<br />
<button type="submit" id="btnUpdate" class="button_AdminPanel" style="width:75px" name="btnSubmit">Update</button>
}
Store Procedure:
PROCEDURE [dbo].[UpdateEmployeeDetails_Sp]
#Emplid int,
#EmplName varchar(40),
#DeptId char(36),
#ShiftId char(40),
#EntryDate char(10),
#Salary varchar(50),
#EmailAdd varchar(50),
#OvertimeApproval bit
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Update HrEmployee
Set EmplName = #EmplName, EntryDate=#EntryDate, BasicSalary=#Salary,
EmailAdd=#EmailAdd, OvertimeApproved= #OvertimeApproval,
DeptID=#DeptId, ShiftID=#ShiftId
where EmplID =#Emplid
END
enclose value attribute value in double quots value="#Item.EmplName". If there is space in the name, Last name (after space) becomes attribute to the input control which is not visible and can't be sent back.
it would be better if you use #Html.TextBoxFor(),this would handle binding as well instead of explicitely setting the textbox value using 'value'
Given that all your code looks reasonable enough, I can only think of a few possibilities:
Perhaps the code that calls your stored procedure from the DataContext has the parameter length for EmplName as something much shorter.
Perhaps the database table has a trigger that is manipulating that column's value.
Perhaps something is going wrong - like an output parameter that is too short - when you retrieve the data from the database and display it.
In Asp.net Entity Framework I need to forward to another page and pass some data processed by the second page along.
In PHP I could do something like
<!-- page1.php -->
<form action="page2.php" method="POST">
<input type="hidden" name="id" />
<input type="submit" value="Go to page 2" />
</form>
<!-- page2.php -->
<?php
echo $_POST['id'];
?>
How can this be implemented in Asp.net?
Edit: There is a simple solution using Javascript and jQuery.
<!-- on page 1 -->
$('input[type=submit]').on('click', function (e) {
// Forward to browsing page and pass id in URL
e.preventDefault();
var id= $('input[name=id]').val();
if ("" == id)
return;
window.location.href = "#Request.Url.OriginalString/page2?id=" + id;
});
<!-- on page 2 -->
alert("#Request.QueryString["id"]");
There are, at least, two options:
Session state, like this:
Putting data into Session (your first page)
Session["Id"] = HiddenFieldId.Value;
Getting data out of Session (your second page)
// First check to see if value is still in session cache
if(Session["Id"] != null)
{
int id = Convert.ToInt32(Session["Id"]);
}
Query string, like this:
Putting the value into the URL for the second page as a query string
http://YOUR_APP/Page2.aspx?id=7
Reading the query string in the second page
int id = Request.QueryString["id"]; // value will be 7 in this example
There's a lot of ways to do this, take a look at this link for some guidance.
HTML page:
<form method="post" action="Page2.aspx" id="form1" name="form1">
<input id="id" name="id" type="hidden" value='test' />
<input type="submit" value="click" />
</form>
Code in Page2.aspx:
protected void Page_Load(object sender, EventArgs e)
{
string value = Request["id"];
}
MVC would look like...
#using (Html.BeginForm("page2", "controllername", FormMethod.Post))
{
#Html.Hidden(f => f.id)
<input type="submit" value="click" />
}
also, read through these MVC tutorials, you shouldn't blindly translate what you know in PHP to ASP.NET MVC, since you need to learn the MVC pattern too.
You can also use <form> with method="POST" in ASP.NET. And get value in code:
int id = int.Parse(Request.Form["id"]);
I have a large recordset being displayed to a user. Each record has an edit button which allows users to edit various data in the record. Certain records have more fields than others so the edit form has various different names and number of fields.
For example one record would produce the following if the edit button is clicked:
<form id="frm1" name="frm1" method="post" action="changeJob.asp?jobNo=1101&jQueryID=1" target="_blank">
<input type='text' name='Qty13' value='8' size="3" maxlength="3"/>
<input type="submit" name="btnFrm1" id="button" value="Submit" />
</form>
However another record would generate this:
<form id="frm2" name="frm2" method="post" action="changeJob.asp?jobNo=1102&jQueryID=2" target="_blank">
<input type='text' name='Qty15' value='8' size="3" maxlength="3"/>
<input type='text' name='Qty16' value='8' size="3" maxlength="3"/>
<input type='text' name='Qty17' value='8' size="3" maxlength="3"/>
<input type='text' name='Qty18' value='8' size="3" maxlength="3"/>
<input type="submit" name="btnFrm2" id="button" value="Submit" />
</form>
As above, each of the input fields is assigned its unique name eg "Qty14" and its form has its own name eg "frm2". These need to be unique because I have some jQuery plus and minus buttons which allow users to increment the quantities.
In changeJob.asp how can I determine which fields are being submitted where they have unique names and number? I can get the form name using a hidden field easily enough.
I am trying to achieve something like:
For Each field in frm1
** Do SQL Update ** Next
Any guidance would be most appreciated :)
Just iterate all the form collection and look for keys starting with the desired name:
Dim strSQL, curValue, blnFirst
blnFirst = True
strSQL = "Update MyTable Set "
For Each key In Request.Form
If Left(key, 3)="Qty" Then
'prevent nasty hacking
If IsNumeric(Replace(key, "Qty", "")) Then
curValue = Request.Form(key)
If IsNumeric(curValue) Then
If Not(blnFirst) Then
strSQL = strSQL & ", "
End If
strSQL = strSQL & key & "=" & curValue
blnFirst = False
End If
End If
End If
Next
If blnFirst Then
'no values, show alert of some sort...
Else
strSQL = strSQL & " Where [filter here]"
'...
End If
This will build dynamic query based on the submitted values.
If each value need separate update the code becomes more simple, hope you can change it yourself. :)
I would love to help. Needing just a bit more info because I don't want to tell you stuff you already know. Can you tell me if you have code already to fill the form... as in... is this form for editing new and/or old data or only new records?
Also, have you thought of having one form but then have your server-side code (ASP) generate input boxes dynamically? This is my recommendation because having more than one form in this case (unless I'm missing something) is ... inelegant.
You can download this zip file which has two asp pages in it that demonstrate a more dynamic approach: http://www.oceanmedia.net/files/hk_config.zip
I am starter with Play Framework. I got a problem when i passed parameters.
I want to pass a collection from view to controller. And i do not know how to do this. I always get "null" when i get a collection from view.
My code below:
Code in controller:
public static void create(List<Book> books) throws Exception {
for(Book book : books){
System.out.println(book.get(0).author) // i got null :(
}
}
Code in HTML
Book 1:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
Book 2:
<input type="text" name="books.author" />
<input type="text" name="books.title" />
When i submit, i want to add 2 records into database include Book1 and Book2. Please support me
Thanks
You can make this work by simplying add the array indicator to your HTML code
Book 1:
<input type="text" name="books[0].author" />
<input type="text" name="books[0].title" />
Book 2:
<input type="text" name="books[1].author" />
<input type="text" name="books[1].title" />
I have tested this solution, and it works fine.
Also note that your println will not compile, as you are calling get(0) on the Book object, and not the List object. If you just println book.author, it outputs the author as required.
In case anyone needs an example of the Javascript for dyanmically adding and removing books (JQUERY needed):
<script type="text/javascript">
$(document).ready(function() {
var bookCount=0;
$('#btnAddBook').click(function() {
bookCount++;
//newElem = go up a to the parent div then grab the previous container
var newElem = $(this).parent().prev().clone().attr('id', 'book[' + bookCount + ']');
//for each input inside the div, change the index to the latest bookCount
$(newElem).find("input").each(function(){
var name = $(this).attr('name');
var leftBracket = name.indexOf("[");
var rightBracket = name.indexOf("]");
var beforeBracketString = name.substring(0,leftBracket+1);//+1 to include the bracket
var afterBracketString = name.substring(rightBracket);
$(this).attr('name', beforeBracketString + bookCount + afterBracketString);
});
//insert it at the end of the books
$(this).parent().prev().after(newElem);
$(newElem).find("input").each(function(){
$(this).attr('id', $(this).attr('id') + bookCount);
});
//enable the remove button
$('#btnRemovebook').removeAttr('disabled');
//If we are at 16 divs, disable the add button
if (bookCount == 15)
$(this).attr('disabled','disabled');
});
$('#btnRemoveBook').click(function() {
bookCount--;
//remove the last book div
$(this).parent().prev().remove();
//in case add was disabled, enable it
$('#btnAddbook').removeAttr('disabled');
//never let them remove the last book div
if (bookCount == 0)
$(this).attr('disabled','disabled');
});
});
</script>
<!-- HTML Snippet -->
<div id="book[0]">
<label> Book: </label>
<input type="text" name="books[0].author" value="Author" />
<input type="text" name="books[0].title" value="Title" />
</div>
<div>
<input type="button" id="btnAddbook" value="Add another book" />
<input type="button" id="btnRemovebook" value="Remove last book" disabled="disabled" />
</div>
<!-- REST of the HTML -->