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
Related
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.
I have a simple form for adding a new teacher. I'm using Spring <form:select> in my view to show a list of teacher's titles, but when I select an option without entering teacher's first and/or last name, since I'm doing validation of all three fields, when the page loads after submit, previously selected option gets lost and "Select title" text appears again.
This is controller:
#RequestMapping(value="/add", method = RequestMethod.POST)
public String postAddTeacher(#RequestParam(value = "title") Integer titleId,
#Validated(Teacher.TeacherChecks.class) #ModelAttribute("teacherAttribute") Teacher teacher,
BindingResult result,
Model model) {
logger.debug("Received request to add new teacher");
if (result.hasErrors()) {
if (titleId != null) {
model.addAttribute("titleList", titleService.getAll());
Title title = titleService.get(titleId);
teacher.setTitle(title);
model.addAttribute("teacher", teacher);
return "addTeacher";
}
else {
model.addAttribute("titleList", titleService.getAll());
return "addTeacher";
}
}
else {
teacherService.add(titleId, teacher);
return "success/addTeacherSuccess";
}
}
This is view:
<c:url var="saveUrl" value="/essays/main/teacher/add" />
<form:form modelAttribute="teacherAttribute" method="POST" action="${saveUrl}">
<form:errors path="*" cssClass="errorblock" element="div" />
<form:label path="title"></form:label>
<form:select path="title" id="titleSelect">
<form:option value="" label="Select title" />
<form:options items="${titleList}" itemValue="titleId" itemLabel="titleDescription" />
</form:select>
<form:errors path="title" cssClass="error"/>
<form:label path="firstName">First name:</form:label>
<form:input path="firstName"/>
<form:errors path="firstName" cssClass="error"/>
<form:label path="lastName">Last name:</form:label>
<form:input path="lastName"/>
<form:errors path="lastName" cssClass="error"/>
<input type="submit" value="Submit" />
</form:form>
Just in case this is Teacher bean:
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "TEACHER_ID", unique = true, nullable = false)
private Integer teacherId;
#NotNull(message = "Teacher's first name is null!", groups = TeacherChecks.class)
#NotBlank(message = "Please enter teacher's first name!", groups = TeacherChecks.class)
#Column(name = "FIRST_NAME", nullable = false, length = 50)
private String firstName;
#NotNull(message = "Teacher's last name is null!", groups = TeacherChecks.class)
#NotBlank(message = "Please enter teacher's last name!", groups = TeacherChecks.class)
#Column(name = "LAST_NAME", nullable = false, length = 50)
private String lastName;
#NotNull(message = "Please choose title!", groups = TeacherChecks.class)
#Valid
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER)
#JoinColumn(name = "TITLE_FK", nullable = false)
private Title title;
#ManyToMany(mappedBy = "teachers")
private Set<Activity> activities;
public Teacher() {
}
// getters & setters
I would like to keep my selected option after page reloads. I though it will happen automatically, like when I enter a value into a text field, it stays there even after the page reloads. Can someone please help me with this? Is there a way to do that from the controller, or it has to be done in the view, and how?
Update:
I added value="${teacherAttribute.title}" to <form:select>, as #willOEM suggested, but it still doesn't work. Now it looks like this:
<form:select path="title" id="titleSelect" value="${teacherAttribute.title}">
<form:option value="" label="Select title" />
<form:options items="${titleList}" itemValue="titleId" itemLabel="titleDescription" />
</form:select>
Your model includes an attribute title that refers to a Title class. This is not the same title you are referring to in your form, which is actually a titleId. Since the titleId is not part of the modelAttribute, it should be excluded from the <form:xxx> tags. You are going to need to use a plain-old <select> tag to pass the selected titleId back to the controller for processing. Unfortunately with a <select> tag, you can't just set the value attribute with JSTL, so you have to conditionally set the seelcted attribute of the option, based on the titleId value (if it is set). If titleList is a simple list of Title objects, you can create your <select> tag this way:
<select id="titleInput" name="titleId">
<option value=""></option>
<c:forEach items="${titleList}" var="title">
<c:when test="${title.titleId== titleId}">
<option value="${title.titleId}" selected>${title.titleName}</option>
</c:when>
<c:otherwise>
<option value="${title.titleId}" >${title.titleName}</option>
</c:otherwise>
</c:forEach>
</select>
In your controller, the #RequestParam annotation will pull the titleId out of the submitted data. Since it is not part of the modelAttribute, you need to make sure this gets added as a model attribute:
...
if (result.hasErrors()) {
if (titleId != null) {
model.addAttribute("titleId", titleId); // <--This line added
model.addAttribute("titleList", titleService.getAll());
Title title = titleService.get(titleId);
teacher.setTitle(title);
model.addAttribute("teacher", teacher);
return "addTeacher";
}
else {
model.addAttribute("titleList", titleService.getAll());
return "addTeacher";
}
}
...
Hopefully we got it this time.
Hello I'm new to cshtml and I have web pages in ASP.NET Razor v2 I would like to insert some data into DB on button click. These data are provided from various textboxes and also uploading picture. May I please know how to how to provide action on button click?
I tried this in my cshtml file :
<button type="submit" name="action" value="insertRegistered">Uložit</button>
#if (action == "insertRegistered")
{
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=#0, FileContent=#1, MimeType=#2 WHERE IDservice=6";
db1.Execute(sql, fileName, fileContent, fileMime);
}
In WebMatrix, you can accomplish this in this way:
Razor code:
#{
var fileName = "";
var fileContent = "";
var fileMime = "";
var IDservice = "";
#*TEST CODE *#
#*if (!IsPost)
{
IDservice = "1";
var db = Database.Open("StarterSite");
var dbCommand = "SELECT * FROM services WHERE IDservice = #0";
var row = db.QuerySingle(dbCommand, IDservice);
fileContent = row.fileContent;
fileMime = row.MimeType;
fileName = row.fileName;
} *#
if (IsPost)
{
fileName = Request.Form["fileName"];
fileContent = Request.Form["fileContent"];
fileMime = Request.Form["fileMime"];
IDservice = Request.Form["IDservice"];
var db1 = Database.Open("StarterSite");
var sql = "UPDATE services SET FileName=#0, FileContent=#1, MimeType=#2 WHERE IDservice=#3";
db1.Execute(sql, fileName, fileContent, fileMime, IDservice);
}
}
And the markup should look like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Service</title>
</head>
<body>
<form method="post">
<fieldset>
<legend>Service Information</legend>
<p><label for="fileName">FileName:</label>
<input type="text" name="fileName" value="#fileName" /></p>
<p><label for="fileContent">File Content:</label>
<input type="text" name="fileContent" value="#fileContent" /></p>
<p><label for="fileMime">Mime:</label>
<input type="text" name="fileMime" value="#fileMime" /></p>
<input type="hidden" name="IDservice" value="#IDservice" />
<p> <button type="submit" name="action" value="insert Registered">Uložit</button></p>
</fieldset>
</form>
</body>
</html>
And here's a working sample.
Here's a set of tutorials which, I believe, should be very helpful!
Put your database logic into a controller action, like this:
public class HomeController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// Do database update logic here
// Upon successfully updating the database redirect to a view
// that displays the information, read-only version not editable
return RedirectToAction("Index");
}
catch(Exception ex)
{
// If something went wrong, then re-display the view
// the user tried to update database from
return View();
}
}
}
Now in your view create a form by using the HTML helper Html.BeginForm(), like this:
#using (Html.BeginForm("ActionMethodName","ControllerName"))
{
... your input, labels, textboxes and other html controls go here
<input class="button" id="submit" type="submit" value="Uložit" />
}
Note: Html.BeginForm() will take everything inside of it and submit that as the form data to the controller action specified as parameters to it.
have been struggling with this. Tried everything I can think of. Im using javascript to pass data to db, works fine with ints on another page but now with strings it wont work :s
#using (Html.BeginForm(null, null, FormMethod.Post, new{#id="manageForm"}))
{
#Html.AntiForgeryToken()
<span class="actions">
#T(User.Id.ToString()) #T(" ") #T(ViewData["Tag"].ToString())
<input type="hidden" name="tag" value="fr" />
<input type="hidden" name="id" value="3" />
#T("Follow")
</span>
}
Javascript
<script type="text/javascript">
function followTag() {
$('#manageForm').attr('action', '#(Url.Action("FollowTag"))').submit();
return false;
}
</script>
Controller
[RequireAuthorization]
[HttpPost]
public ActionResult FollowTag(int id, string tag)
{
_service.FollowTag(id, tag);
return RedirectToAction("TagPage","Detail", new
{
});
}
Data Access
public void FollowTag(int id, string tag)
{
DbCommand comm = GetCommand("SPTagFollow");
//user id
comm.AddParameter<int>(this.Factory, "id", id);
//id to follow
comm.AddParameter<string>(this.Factory, "tag", tag);
comm.SafeExecuteNonQuery();
}
route is setup fine and sql(stored procedure) executes perfect. Hopefully one of you can see something obvious
cheers
I think is a problem of mistyping, check your last <a> tag, you typed following.() in the onclick event, see that your javascript function is called followTag.
If that doesn't fix it, then get rid of that foolowTag function, you can specify the action and the controller in the form itself, like this:
#using (Html.BeginForm("FollowTag", "YourControllerName", FormMethod.Post)) {
...
//Delete this line
//#T("Follow")
//This submit button will do the job
<input type='submit' value='#T("Follow")' />
}
That should do it. If you are using the anchor tag just for styling that's ok, otherwise you should use the other way, I think is clearer and besides it takes advantage of razor's great features.
I've a MVC application, whose SharedLayout view(Master Page) gives user capability to search. They could search their order by Order No or By Bill no. So there are two option buttons the Shared View along with the textbox. Code is somewhat like this
#using (Html.BeginForm("Track", "Tracking", FormMethod.Post))
{
<div style="text-align: center">
<textarea cols="20" id="txtNo" name="txtOrderNo" rows="2" ></textarea>
</div>
<div style="text-align: center">
<input type="radio" name="optOrderNo" checked="checked" value="tracking" />Order No <input type="radio" name="optRefNo" value="tracking" />Ref No
</div>
<div style="text-align: center">
<input type="submit" value="Track" />
</div>
}
So it'll go to TrackingController and Track Method in it and return the view. It works fine for a single search as a View is associated with a controller's methods. It works fine but how could i conditionally return the other view based on the radio button selection.
What i come up with is this
[HttpPost]
public ActionResult Track(FormCollection form)
{
string refNo = null;
if (form["optRefNo"] == null)
{
string OrderNo = form["txtOrderNo"];
var manager = new TrackingManager();
var a = manager.ConsignmentTracking(OrderNo);
var model = new TrackingModel();
if (OrderNo != null)
model.SetModelForConsNo(a, consNo);
return View(model);
}
refNo = form["txtConsNo"];
return TrackByRef(refNo);
}
public ActionResult TrackByRef(string refNo)
{
//what ever i want to do with reference no
return View();
}
Kindly guide.
Thanks
View has an overload where the first parameter is a string. This is the name (or path) to the view you want to use, rather than the default (which is a view that matches the action's name).
public ActionResult TrackByRef(string refNo)
{
//what ever i want to do with reference no
return View("Track");
// or, if you want to supply a model to Track:
// return View("Track", myModel);
}