How to display properties of specific object selected via dropdown? - spring-mvc

I wrote a query in which I get the semester class, display its values ​​as a name and get its id. Accordingly, when I select the semester I need in the drop-down list, I am given the semester that I chose. But I also need to display its duration in another field, I can do this if I create a ForEach loop and use it to extract this value, but it displays absolutely all the available values, and not the one I need. Tell me how to do it right? For display I use Spring MVC. Now the page looks like this:
I am also attaching the jsp content:
<form:form action="allSemestrsSem" method="get" id="selectSemestr" modelAttribute="semestr">
<tr>
<td style="font-size: large;">Select semester</td>
<td style="padding-left: 50px">
<select name="selectSemestr">
<c:forEach items="${semestr}" var="semestr">
<option value="${semestr.id}">${semestr.name}</option>
</c:forEach>
</select>
</td>
<td style="padding-left: 20px">
<security:authorize access="hasRole('ADMIN')">
<input type="submit" id="button" value="select" /></td>
</security:authorize>
</tr>
<tr height="80px" style="font-size: large; font-weight: bold;">
<td colspan="3">Semester duration:
<c:forEach items="${semestr}" var="semestr"> ${semestr.duration} </c:forEach>
</td>
</tr>
</form:form>
And just in case my controller is:
#RequestMapping(value = "/allSemestrsSem", method = RequestMethod.GET)
public String allSemestrs(#RequestParam(name = "selectSemestr") String selectSemestr, Model model) {
List<Semestr> semestr = service.getSemestr();
model.addAttribute("semestr", semestr);
List<Discipline> allDisciplines = service.getDisciplineSemestrId(Integer.valueOf(selectSemestr));
model.addAttribute("allDisc", allDisciplines);
return "semestr";
}

Related

Spring #ModelAttribute not working

I have a controller in which I put both the get and post methods. Both methods work fine but when I introduce #ModelAttribute annotation to the POST method, it starts giving me Status 400 -- The request sent by the client was syntactically incorrect.
I do not know what I am doing wrong. The View looks like:
<form:form method="post" action="createIdeaPublic" commandName="idea">
<table class="form">
<tr>
<td align="right"><label for="title">Idea Title</label></td><td align="left"><form:input type="text" path="title" id="title"></form:input></td>
<td align="right"><label for="email">Your Email</label></td><td align="left"><form:input type="text" path="requestorEmail" id="requestorEmail" class="emails"></form:input></td>
</tr>
<tr>
<td align="right"><label for="partnerEmail">CI Contact Email</label></td><td align="left"><form:input type="text" path="cIInitialContact" id="cIInitialContact" class="emails"></form:input></td>
<td align="right"><label for="sponsorEmail">Sponsor Email</label></td><td align="left"><form:input type="text" path="sponsorEmail" id="sponsorEmail" class="emails"></form:input></td>
</tr>
<tr>
<td align="right"><label for="requestedDeliveryDate">Requested Delivery Date</label></td><td align="left"><form:input type="text" path="requestedDeliveryDate" id="requestedDeliveryDate" class="datepicker"></form:input></td>
<td align="right"><label>Classification</label></td><td align="left">
<label for="discretionary" class="radio">Discretionary</label>
<form:radiobutton path="stateDescription" id="discretionary" value="Discretionary"></form:radiobutton>
<label for="mandatory" class="radio">Mandatory</label>
<form:radiobutton path="stateDescription" id="mandatory" value="Mandatory"></form:radiobutton>
<label for="regulatory" class="radio">Regulatory</label>
<form:radiobutton path="stateDescription" id="regulatory" value="Regulatory"></form:radiobutton>
</td>
</tr>
<tr>
<td colspan="4" align="right"><input type="submit" class="ui ui-button ui-corner-all ui-widget" style="margin-top: .6em; margin-right: 1em;font-weight: bold;font-size: 1.2em; width: 150px;" value="Create Idea" /></td>
</tr>
</table>
</form:form>
I tried changing the commandName="idea" to modelAttribute="idea" but no benifit.
The Spring controller looks like
#Controller
#RequestMapping ("/createIdeaPublic")
public class CreateIdeaPublicController{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView view(ModelMap model) {
model.addAttribute("areas",Utils.areas);
return new ModelAndView("createIdeaPublic", "idea", new Idea());
}
#RequestMapping(method = RequestMethod.POST)
public String submit(#ModelAttribute("idea")Idea idea, ModelMap model) {
// System.out.println(idea.getTitle());
System.out.println("Hello World");
return "redirect:createIdeaPublic";
}
}
But as soon as I remove the #ModelAttribute("idea")Idea idea, from the submit method, the form submission starts working.
I figured it out. It was issue with the date field. If I dont enter a value into the date field, I would get 400 page. So here is what I did in the Controller class. Copy as it is if you have this issue (Just change the date format accordingly).
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
dateFormat.setLenient(false);
// true passed to CustomDateEditor constructor means convert empty String to null
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

The issue with cascading dropdown lists using ajax and HDIV

I integrated HDIV and Spring MVC. Now I have a form on which there are three dropdown lists contract, taskorder and subtask. The select change of contract will update the content of taskorder dropdown list via ajax and then the select change of the task order will update the content of dropdown list subtask via ajax. The form looks like this:
<c:url var="url" value="/admin/user/newstafftask" >
<c:param name="_MODIFY_HDIV_STATE_" value="${taskOrder.id}" />
</c:url>
<form:form action="${url}" commandName="newRequestStaffTasks">
<form:hidden path="subId" />
<table >
<tr>
<td> <label>Contract </label></td>
<td>
<form:select path="newRequestStaffContract.id">
<option></option>
<form:options items="${contractList}" itemValue="id" itemLabel="contract.contractNbr" />
</form:select>
</td>
</tr>
<tr>
<td> <label>Task Order </label></td>
<td>
<form:select path="taskOrder.id">
</form:select>
</td>
</tr>
<tr>
<td> <label>SubTask Code </label></td>
<td>
<form:select path="subtask.subTaskId">
<option></option>
</form:select>
</td>
</tr>
</table>
</form:form>
When I tried to submit the form, I got the error message "INVALID_PARAMETER_NAME" about the taskOrder.id. I understand the problem is the values of two dropdown lists were updated on the client side.I tried _MODIFY_HDIV_STATE_, but it did not work with this case. So I am not sure how to deal with it now. Please help. Thanks.
Update 1
I already exclude the Ajax request from the HDIV validation. Below is the code snippet that update taskOrder list when the contract select change:
$(".modal-body").on("change", "#newRequestStaffContract\\.id", function() {
getTaskOrderByContract($(this));
});
function getTaskOrderByContract(o) {
contractId = o.val();
if (contractId) {
$.get("../../ajax/getTaskOrderByContract", {
contractId : contractId
}
, function(data) {
var options = '<option value=""></option>';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i].id + '">' +data[i].taskNum+ '</option>';
}
$('#taskOrder\\.id').html(options);
});
};
};

Multiple foreach in Durandal

I am all new to Durandal and have been playing around with it for a few hours now. It seems very promising - but now I have run into a problem, I cannot figure out - and cannot find a solution with Google.
I have a view with three tables of data - creditCardLines, cashLines and drivingReimbursementLines. They fetch data from three different data sources - and the user can add new lines to cashLines and drivingReimbursementLines (left out the forms).
Problem: In the viewmodel, I can easily bind a list for data to the first foreach - but I cannot figure out how to bind data to the second and third.
In the activate function I make an ajax call to my server API to get the data for the first foreach - and then returns the promise, when this finishes. How do I get data for the second and third foreach here?
ViewModel:
define(function () {
var submit = function () {
this.displayName = 'Expenses';
this.creditCardLines = ko.observableArray();
var me = this;
this.activate = function () {
return $.get('/submit/GetCreditCardLines').then(function (creditCardLines) {
me.creditCardLines(creditCardLines.Data);
});
};
};
return submit;
});
View:
<section>
<h2 data-bind="html:displayName"></h2>
<h3>CreditCard lines</h3>
<table class="table">
<tbody data-bind="foreach: creditCardLines">
<tr>
<td class="date" data-bind="text: Date"></td>
<td data-bind="text: Description"></td>
<td data-bind="text: Amount"></td>
<td><input type="checkbox" data-bind="checked: ApprovedEmployee" /></td>
</tr>
</tbody>
</table>
<h3>Cash lines</h3>
<table class="table">
<tbody data-bind="foreach: cashLines">
<tr>
<td class="date" data-bind="text: Date"></td>
<td data-bind="text: Description"></td>
<td data-bind="text: Amount"></td>
</tr>
</tbody>
</table>
<!-- TODO: Generate form to add new lines -->
<h3>Driving reimbursement lines</h3>
<table class="table">
<tbody data-bind="foreach: drivingReimbursementLines">
<tr>
<td class="date" data-bind="text: Date"></td>
<td data-bind="text: Description"></td>
<td data-bind="text: Distance"></td>
<td data-bind="text: Rate"></td>
<td data-bind="text: Amount"></td>
</tr>
</tbody>
</table>
<!-- TODO: Generate form to add new lines -->
<!-- Approve and save all lines as a quote with lines -->
<input type="submit" value="Submit quote" />
</section>
This is how I've been dealing with multiple jQuery deferred calls in my view models:
return $.when(
$.get('/submit/GetCreditCardLines'),
$.get('/submit/GetCashLines'),
$.get('/submit/GetReimbursementLines'))
.then(function (creditCardLines, cashLines, reimbursementLines)
{
processCreditCardLines(creditCardLines);
processCashLines(cashLines);
processReimbursementLines(reimbursementLines);
})
.fail(function (status)
{
// Do whatever you need to if it fails
});
You don't need the process methods if you don't want them, but if you're doing anything complicated, I think it's neater to have them.
You should check out BreezeJS. It has an option to make a single Ajax call to pull multiple lookups.
Take a look at the BreezeJS docs for a detailed explanation: http://www.breezejs.com/documentation/lookup-lists

ASP.net looping through table

I was wondering if any one could help me out; I have a table which looks something like the following:
<table id="Table1" border="0">
<tr>
<td><b>1.</b> Question 1</td>
</tr><tr>
<td style="border-width:5px;border-style:solid;"></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer1</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer2</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer3</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio1" type="radio" name="Group1" value="Radio1" /><label for="Radio1">Answer4</label></td>
</tr><tr>
<td style="height:30px;"></td>
</tr><tr>
<td><b>2.</b> Question 2</td>
</tr><tr>
<td style="border-width:5px;border-style:solid;"></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio2" type="radio" name="Group2" value="Radio2" /><label for="Radio2">yes</label></td>
</tr><tr>
<td align="left" style="width:1000px;"><input id="Radio2" type="radio" name="Group2" value="Radio2" /><label for="Radio2">no</label></td>
</tr><tr>
<td style="height:30px;"></td>
</tr>
</table>
How do I go about looping through each group of radio buttons and getting the text of the selected radio button?
The code displayed above is created dynamically ... in my aspx file I have the following code:
<asp:Table ID="Table1" runat="server">
</asp:Table>
If you want to access the rows in ASP.NET (on the server side), you need to convert the table, rows and the cells to server control (using runat="server") and iterate through the controls in the table.
EDIT : :- If you are adding the rows, cells and radionbuttons following way, all of them will be the server controls (and are runat=server) so that you can access them the way I mentioned above:--
// Create new row and add it to the table.
TableRow tRow = new TableRow();
table1.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++)
{
// Create a new cell and add it to the row.
TableCell tCell = new TableCell();
RadioButton rdb = new RadioButton();
rdb.ID = "rdb_" + cellCtr.ToString();
rdb.Text = "radio button";
rdb.GroupName = "rdbGroup";
tCell.Controls.Add(rdb);
tRow.Cells.Add(tCell);
}
EDIT:-
You can find the controls in each cell.Something like below:-
foreach(TableCell cell in tableRow.Cells)
{
foreach(Control ctrl in cell.Controls)
{
if(ctrl is RadioButton)
{
if(ctrl.Selected)
{
string rdValue=ctrl.Text;
}
}
}
}
Or If you want to iterate on the client side using Javascript, have a look here and you dont have to apply runat="server".
It sounds like you're starting with a barebones <table> in your markup page, and dynamically adding those <input> afterwards.
Consider taking this approach:
Add the runat="server" attribute to your table.
In the code where you're adding those <input> tags, add a new RadioButton control. Use an ID here that you can predict later. Perhaps you can use a RadioButtonList instead, if the choices are logically grouped!
It's unclear if you're manually adding those <tr> and <td> as strings. Consider the option of new TableRow() and new TableCell(). Then add the new RadioButton to the TableCell.Controls collection with tc.Controls.Add(myNewRadioButton);
In your postback code, simply refer to your RadioButton controls by id, or even loop through the Controls collection property of the Table1.
foreach (Control x in Table1.Controls)
{
if (x.GetType().ToString().Equals("System.Web.UI.WebControls.RadioButton"))
{
if (((RadioButton)x).Checked)
{
//proceed.
}
}
}
Convert all controls to server controls (by adding the runat="server" attribute). You can then programatically access what you need o. The server.

Can't Get ASP.NET MVC Form To Post

I am having problems getting my form to Post to my Save method in a controller. I am new to MVC, and have followed several examples to try to get this to work. Here is my html markup:
<form action="Edit/Save" method="post">
<fieldset>
<legend>Personal Information</legend>
<table class="editGrid">
<tr>
<td><label for="txtFirstName">First Name:</label></td>
<td><input type="text" id="txtFirstName" value="<%=user.FirstName %>" name="FirstName" /></td>
</tr>
<tr>
<td><label for="txtLastName">Last Name:</label></td>
<td><input type="text" id="txtLastName" value="<%=user.LastName %>" name="LastName" /></td>
</tr>
<tr>
<td><label for="txtNtLogin">NT Login:</label></td>
<td><input type="text" id="txtNtLogin" value="<%=user.NtLogin %>" name="NtLogin" /></td>
</tr>
<tr>
<td><label for="txtHireDate">Hire Date:</label></td>
<td><input type="text" id="txtHireDate" value="<%=string.Format("{0:d}",user.HireDate) %>" name="HireDate" /></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Job Information</legend>
<table class="editGrid">
<tr>
<td><label for="CostCenters">Cost Center:</label></td>
<td><%=Html.DropDownList("CostCenters")%></td>
</tr>
<tr>
<td><label for="Managers">Manager:</label></td>
<td><%=Html.DropDownList("Managers")%></td>
</tr>
<tr>
<td><label for="Responsibilities">Responsibility:</label></td>
<td><%=Html.DropDownList("Responsibilities")%></td>
</tr>
<tr>
<td><label for="Departments">Department:</label></td>
<td><%=Html.DropDownList("Departments")%></td>
</tr>
<tr>
<td><label for="Active">Active:</label></td>
<td><%=Html.CheckBox("Active",user.Active) %></td>
</tr>
<tr>
<td><label for="txtHireDate">Hire Date:</label></td>
<td><%=Html.TextBox("txtHireDate",string.Format("{0:d}",user.HireDate)) %></td>
</tr>
<tr>
<td><label for="txtReleaseDate">Release Date:</label></td>
<td><%=Html.TextBox("txtReleaseDate",string.Format("{0:d}",user.ReleaseDate)) %></td>
</tr>
</table>
</fieldset>
<input type="submit" value="Save Changes" />
</form>
This form routes to a Save method in my EditController. Here is the code for my EditController's Save method:
public class EditController : Controller
{
public ActionResult Save()
{
//Save code goes here
}
I have tried using the html form tag, and also the Html helper code:
using (Html.BeginForm("Save", "Edit"))
Here is the entry from my RegisterRoutes method in the Global.asax file:
routes.MapRoute("EditSave", "{controller}/Save",
new { controller = "Edit", action = "Save" });
No matter what I do, the submit button does not trigger the Save method. Yet, if I manually key in the Url, The code breaks right into the Save method.
Edit:
Per Craig Stuntz's comment, I checked the source of the page. The page actually contains 2 forms, although only 1 is coded on the page by myself: Here is the HTML that appears prior to my form tag:
<form name="aspnetForm" method="post" action="44" id="aspnetForm">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjM3OTAyNTUzZGQrHhVn9+t78aHxN0vHvKUJ8DQWlQ==" />
</div>
<div id="nav">
<span id="navLinks">
Placeholder Link
</span>
<span id="userName">
<span id="ctl00_lblUserName" class="UserName">Welcome, Test User</span>
</span>
</div>
<div id="Content">
<div id="formContainer">
<form action="Edit/Save" method="post">
I didn't think MVC generated viewstate or additional form tags. I am pulling data and populating it into this form using another method from the same controller. Am I doing something wrong here?
Ok, got the answer. And thanks Craig for having me look at the HTML again! My master page had generated a form tag in it without my knowing it, so I essentially had nested forms on the same page. After I removed the form from the Master Page, everything worked perfectly.

Resources