Value is splited into half before submission - asp.net

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.

Related

How to pass variable from hidden input box to another page

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>

Strange behavior of ASP.NET MVC Razor engine with unobtrusive validation attributes

I've just faced a really strange behavior of Razor engine regarding adding unobtrusive validation attributes to inputs in forms. In some cases attributes are not added.
So, I have two similar forms on the same page with similar input elements. They must be submitted to different url's.
From model side, I have a few DataAnnotations Attributes, applied to properties to have a client-side validation.
Here is my a bit simplified code of ViewModel:
public class ApplicantPersonalInfo
{
[Required]
[Display(Name = "First Name")]
[StringLength(20, MinimumLength = 2)]
[RegularExpression(#"^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$", ErrorMessage = "First Name is in incorrect format")]
public string FirstName { get; set; }
}
Now I want to create two forms. For every of them action url can differ dynamically (I submit them using ajaxSubmit from jQuery Form Plugin), that's why I decided not to use Html.BeginForm helper method, instead creating them with simple <form> tag. So my code is:
<form id="form1">
#Html.TextBoxFor(m => Model.FirstName, new { id = "firstName1" })
</form>
<form id="form2">
#Html.TextBoxFor(m => Model.FirstName, new { id = "firstName2" })
</form>
And the most interesting is the resulting html code:
<form id="form1">
<input data-val="true" data-val-length="The field First Name must be a string with a minimum length of 2 and a maximum length of 20." data-val-length-max="20" data-val-length-min="2" data-val-regex="First Name is in incorrect format" data-val-regex-pattern="^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$" data-val-required="The First Name field is required." id="firstName1" name="FirstName" type="text" value=""/>
</form>
<form id="form2">
<input id="firstName2" name="FirstName" type="text" value=""/>
</form>
See? All those validation attributes are not applied to the second input!
BUT if the form is generated using Html.BeginForm, like this:
#using (Html.BeginForm("NotExistingController", "NotExisitngAtion", FormMethod.Post, new { id = "form1" }))
{
#Html.TextBoxFor(m => Model.HomeOwner.FirstName, new { id = "firstName1" })
}
<form id="form2">
#Html.TextBoxFor(m => Model.HomeOwner.FirstName, new { id = "firstName2" })
</form>
the resulting html code is with attributes in both inputs:
<form action="/NotExisitngAtion/NotExistingController" id="form1" method="post">
<input data-val="true" data-val-length="The field First Name must be a string with a minimum length of 2 and a maximum length of 20." data-val-length-max="20" data-val-length-min="2" data-val-regex="First Name is in incorrect format" data-val-regex-pattern="^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$" data-val-required="The First Name field is required." id="firstName1" name="FirstName" type="text" value="" />
</form>
<form id="form2">
<input data-val="true" data-val-length="The field First Name must be a string with a minimum length of 2 and a maximum length of 20." data-val-length-max="20" data-val-length-min="2" data-val-regex="First Name is in incorrect format" data-val-regex-pattern="^[ÀàÂâÆæÇçÉéÈèÊêËëÎîÏïÔôŒœÙùÛûÜüŸÿa-zA-Z \.‘'`-]+$" data-val-required="The First Name field is required." id="firstName2" name="FirstName" type="text" value="" />
</form>
I'm really confused by this behavior. And I've tried - you can add as much forms as you want using Html.BeginForm - every of them will have set of validation attributes; but if you add >1 form using simple <form> tag, starting from the second one attributes are missing.
So am I missing something or it's a bug in Razor engine?

ID not passing to Controller

My drop down doesn't send EmplID to Controller, why ? All other drop down does but not this one, why ? i tried a lot
This view contains DropDown
View:
#using (Html.BeginForm("DeactivateAdmin", "Home", FormMethod.Post))
{
<fieldset>
<label id="lblDD">Select Admin</label>
<br />
#Html.DropDownList("EmplID_Admin", "Select Name")
<br />
<br />
<input type="submit" class="button_form" style="Width: 10.5% !important" value="Delete Admin" />
</fieldset>
}
This controller shoud accept value but emplID is null
Controller:
public ActionResult DeactivateAdmin(int? emplID)
{
if (!String.IsNullOrEmpty(Session["Admin"] as string))
{
var DeactiveAdmin = DataContext.DeActivateAdmin_Sp(emplID);
}
else
{
return RedirectToAction("IsAuth_Page.cshtml", "Home");
}
return View();
}
SP:
ALTER PROCEDURE [dbo].[DeActivateAdmin_Sp]
#emplID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Update HrEmployee
Set EmployeeType = 2 where EmplID= #emplID
END
the parameter is different naming than what you have assigned to your drop down list. they must match

Classic ASP - submitting unknown number and name of fields?

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

Using ASP.NET Razor Edit Data Page in WebMatrix

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>

Resources