In JSP how do I make a GET request on selection of one dropdown value and get data for other dropdowns from DB? - spring

Hi All please suggest me some approaches for the below problem
Spring boot MVC: UI page is JSP
Currently All dropdown values are getting from DB when the home page is opened
I am stuck at the below task
On selection of one dropdown value, the below other dropdown values should be auto populated in jsp before the form is submitted
How do I make a GET request on selection of one dropdown value and get data for other dropdowns from DB?
below is the sample jsp form
enter image description here

if you using jquery with jsp then , use Ajax POST in Change event of name-3 dropdown , on success function populate on name-4 , name-5 drop down.
Like,
$(document).on('change','#name3',function(){
callAjaxByObj({
"url" : "url",
"type" : "POST",
"data" : {"name3Id" : $(this).val()},
"resp" : afterSuccess(),
"error" : ajaxFailed()
});
});
function afterSuccess(){
return function(resp){
// here you can populate Selected data on name-4, name-5 dropdowns use below
$("#name4").val(resp.name4Id);
$("#name5").val(resp.name5Id);
// OR if you want to append new drop down values to append name4, name5 dropdowns
var htm='';
var index = 0;
var obj = '';
for(index = 0; index < resp.name4List.length; index++) {
obj = resp.name4List[index];
htm +='<option value="'+obj.id+'" >'+obj.name+'</option>';
}
$("#name4").append(htm);
// same way you can do for name5 drop down.
}
}

Related

How to replace button with text based on the id attribute from html to ajax

I have many products and each products have buttons with different attribute IDs. On click of that button, the attribute of the button is passed to ajax function and I am able to get different attribute ID when I give them in alert message.
Now I want to replace the button with a text based on that attribute ID.
html code:
<button bookid='".$row['bookid']."' id='book' type='button'>Add</button>
My ajax code is:
$("body").delegate("#book","click",function(event){
event.preventDefault();
var bid = $(this).attr('bookid');
$.ajax({
url : "login_action.php",
method : "POST",
data : {addToStore:1,bookid:bid},
success : function(msg){
if(msg == 0){
alert('Already 1 product is added ');
}else{
$(bid).text('Added');
}
}
})
})
The problem is I am not able to replace the button with the text "Added".

display the selected value from DropDown in a page

Hi Folks i am retrieving Name from database to drop down list. Now i want to display the selected value from DropDown in a page. My code is like follows to retrieve data,am using Fluent data as a framework.
My Controller Action is
var query = Abc.GetProducts();
ViewBag.EnterpriseId = new SelectList(query.AsEnumerable(), "EnterpriseId", "Name");
return View();
My view is ,
#Html.DropDownList("EnterpriseID", (SelectList) ViewBag.EnterpriseID, "--Select Resource--")
You can use a simple js for this:
elem = $('.selectClass');
options = elem.find('option[value="'+DataFromDBHere+'"]');
if(options){
options.prop('selected', 'selected');
}

Custom grid button to load ajax content depending on selected row

I need to make a custom buttom in my grid that will open a modal which will render a select field with options depending on selected row.
So the user will select a row and click the button. The row id should be passed as an url parameter to my action so that it can make a query and populate the select field.
This is where I'm struggling:
navigatorExtraButtons="{
honorarios:{
title: 'Consultar honorários do processo',
caption: 'H',
icon: 'none',
onclick: function(){
var id = jQuery('#processoTable').jqGrid('getGridParam','selrow');
if (id) {
var ret = jQuery('#processoTable').jqGrid('getRowData',id);
// need to pass ret.nrProcesso as param to the URL that will load content into the modal
} else { alert('Please select a row.');}
}
},
With above code I can get the desired ID value from selected row. But I don't know how to assign it to a
<s:url... param
and populate a modal...
Thanks in advance.
I've found a solution. Posting here hoping it might help someone else.
I've ended up using plain old jquery script to get the modal to show up instead of jquery-plugin.
Just construct your action url adding desired parameter and call an ajax function:
<sj:submit id="consulta_honorarios" value="Consultar Honorários" onClickTopics="honorarios" button="true"/>
<sj:dialog
id="mydialog"
title="Consultar honorários"
autoOpen="false"
modal="true"
dialogClass="ui-jqdialog"
/>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#consulta_honorarios").click(function(){
var actionURL = '<s:property value="%{advprocselecturl}" />';
var id = jQuery('#processoTable').jqGrid('getGridParam','selrow');
if (id) {
var ret = jQuery('#processoTable').jqGrid('getRowData',id);
actionURL += '?nrProcesso=' + ret.nrProcesso;
// alert('id='+ret.nrProcesso+' / actionURL='+actionURL);
jQuery.ajax({
url: actionURL
}).done(function(data){
jQuery('#mydialog').html(data).dialog('open');
});
} else {
jQuery('<div />').html('Por favor, selecione um registro.').dialog();
}
});
});
In your action you must declare a variable with the same name as your url parameter (nrProcesso in my case) with respective getter and setter.

MVC 3 Reload current page with modified querystring values

Background:
I have an MVC layout (master) view which uses #Html.RenderAction to display a dropdown in the left side navigation panel. This dropdown will be displayed on all the pages of the site.
The dropdown is wrapped in a form element and on change of the dropdown the form is posted.
Question:
Now, once the form is posted, I need to reload the contents of the current page (whatever page the user is currently on...) with the value of the dropdown attached in the querystring. This would mean replacing the value which might already be there in the querystring from a previous selection.
Example:
The user navigates to the Home page of the website:
Url: /Home/?dropdownvalue=blue
At this point the dropdown displays 'Blue' as selected. The user changes the value in the dropdown to 'Red'. I need to reload the page with the following url -
/Home/?dropdownvalue=red
The user moves to another page in the site:
Url: /CustomerFavorite/?dropdown=red
Change the value in the dropdown from 'Red' to 'Green'.
The 'CustomerFavourite' page should be reloaded with 'Green' in querystring.
I apologize for the lenghty post. But, thought of providing some extra information to clarify the issue.
Thanks.
Thanks to Darin for providing the link for javascript manipulation of the querystring. But, I wanted a server side solution so here's how I implemented it -
public ActionResult _ColorSelection(ColorModel model)
{
string selectedColor = model.Color.Value;
// Modify Querystring params...
NameValueCollection querystring =
HttpUtility.ParseQueryString(Request.UrlReferrer.Query); // Parse QS
// If Querystring contains the 'color' param, then set it to selected value
if (!string.IsNullOrEmpty(querystring["color"]))
{
querystring["color"] = selectedColor;
}
else // Add color key to querystring
{
querystring.Add("color", selectedColor);
}
// Create new url
string url = Request.UrlReferrer.AbsolutePath
+ "?" + querystring.ToString();
return Redirect(url); // redirect
}
You may try using a GET method of the form in which the drop down is wrapped:
#using (Html.BeginForm(null, null, FormMethod.Get))
{
#Html.Action("SomeActionThatRendersTheDropDown", "SomeController")
}
or maybe the entire form is wrapped inside the action:
#Html.Action("SomeAction", "SomeController")
and then in javascript subscribe to the change event of the dropdown and trigger the submission of the form:
$(function() {
$('#DropDownId').change(function() {
$(this).closest('form').submit();
});
});
Because you have used GET request, this will automatically reload the current page sending the value of the dropdown in the query string.
If you are using jQuery you can create a function that will post the selected value in your list.
$(document).ready(function () {
$("#ListId").change(function () {
$.ajax({
url: "CustomerFavorite/Edit",
type: "POST",
data: "colour=" + $("#ListId").val(),
success: function (result) {
//Code to update your page
}
},
error: function () {
}
}

WebMatrix UrlData collection not getting filled in MVC

I have an MVC 3 application which employs WebMatrix in one of its pages.
I have something like this in the page:
string s1 = UrlData[0];
var query = "select * from test where id = " + UrlData[1];
// Open the database of the service delivery
var dataBase = Database.Open("connection_string");
var results = database.Query(query);
There is an MVC Dropdownlist in the page and in the onchange event of this dropdownlist i am submitting the MVC form. It goes to the controller method which has this dropdownlist value as the parameter and after some operations is redirected back to the same page using RedirectToAction().
But, the UrlData collection does not have any values. Could some one help me out with this?
Thanks
Nidhin
UrlData is sorta like a Querystring with the execption that each value is located by position not by name. So if you where to have Url like http://localhost:6324/A/B/C/D in you Default.cshtml page and you did the following code:
<p>Total number of items in UrlData: #UrlData.Count</p>
<ul>
#for(var i = 0; i < UrlData.Count; i++){
<li>UrlData[#i]: #UrlData[i]</li>
}
</ul>
the output would look like
UrlData[0] : A
UrlData[1] : B
UrlData[2] : C
UrlData[3] : D
To clarify even further here is a "fantastic" article on the subject
UrlData

Resources