Dynamically Populate Drop down List In Spring MVC - spring

I am new to Spring MVC. I have two Dropdown Lists in Jsp.One for country and Other for State. As soon as i select country from list State list should be populated with respective lists.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My Controller Program:
public #ResponseBody HashMap<String, String>
showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, ModelMap model) {
HashMap<String,String> statelist = new HashMap<String,String>();
List<States> statelist = new ArrayList<States>();
if (country.equals("UnitedStates")) {
statelist.put("Al","Alaska");
statelist.put("Tl","Texas");
} else if (country.equals("India")) {
statelist.put("Mh","Maharashtra");
statelist.put("WB","West Bengal");
statelist.put("KR","Karnataka");
statelist.put("AP","Andhra Pradesh");
statelist.put("TN","Tamil Nadu");
}
return statelist;
}
I am not getting the response from controller. How to access the hasmap in jsp. Please Help me. Thanks.

I think you should change your method like below.
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public #ResponseBody HashMap<String, String> showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, ModelMap model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
return stateMap;
}
Then on JSP you can simply iterate this map,like below.
<c:forEach items="${state.stateMap}" var="data" varStatus="status">
<tr>
<td>${data.value}</td>
</tr>
</c:forEach>

shearing my solution. because i was stuck in same condition.
html page
$(document).ready(function() { // for client name
$('#example').change(function(event) {
var country = $("select#example").val(); // country = define value of selected option
$.getJSON('ajaxAction0', {
ptype : country
}, function(data) {
var select = $('#clientname');
select.find('option').remove();
$.each(data, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
});
});
<div>
<select class="form-control" name="example" id="example">
<option value="0">ALL</option>
<option th:each="dropdown : ${dropdown}" th:value="${dropdown.id}"
th:text="${dropdown.tagName}"></option>
</select> <select class="form-control" name="clientname" id="clientname">
<option value="0">ALL</option>
<option th:each="dropd : ${drpdwn}" th:value="${dropd.id}"
th:text="${dropd.tagName}"></option>
</select>
<button id="w-button-search" type="button">Search</button>
</div>
controller code for first drop down
#RequestMapping(value = "/dropdown", method = RequestMethod.GET)
public String dropDown(Model model) {
List<Tag> data = new ArrayList<>();
data.add(new Tag(1, "ruby"));
data.add(new Tag(2, "rails"));
data.add(new Tag(3, "c / c++"));
data.add(new Tag(4, ".net"));
data.add(new Tag(5, "python"));
data.add(new Tag(6, "java"));
data.add(new Tag(7, "javascript"));
data.add(new Tag(8, "jscript"));
model.addAttribute("dropdown", data);
return "dropDown";
}
second drop down code is
Map <\string, string> udata = null;
#RequestMapping(value = "ajaxAction0", method = RequestMethod.GET)
public #ResponseBody Map<String, String> findAllAgencies(
#RequestParam(value = "ptype", required = true) String ptype) {
udata = new HashMap<>();
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
List<UserRecord> user = em
.createNativeQuery("Select id, name, email from user_Record where id = :uid", UserRecord.class)
.setParameter("uid", ptype).getResultList();
for(UserRecord ur:user) {
udata.put(ur.getEmail(), ur.getName());
}
return udata; }
hope it will help.

You can obtain a list of states based on the country:
#Autowired
StateService stateService;
#GetMapping("/states")
public #ResponseBody List<State> getStates(#RequestParam String country) {
return stateService.getStates(country) ;
}
your State class will contain code and name;
$("select#country").change(function() {
var countryVal = $("#country").val();
$.ajax({
url : '/states?country='+countryVal,
method : 'GET',
},
success: function (states) {
var stateSelect = $('#state'); // the state select element
stateSelect.find('option').remove();
for (i = 0; i < states.length; i++) {
stateSelect.append("<option value=" + states[i].code + " >" + states[i].name + "</option>")
}
},
error :function()
{
alert("error");
}
});

Related

Post ajax values to MVC Action Result

Ok, so I have the following Ajax get request going to a [HttpPost] controller method in an ASP.NET MVC 5 application.
The javascript function shown here successfully posts the values to the server side:
<script>
function get_row() {
var one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
var two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
var result = one + "," + two;
//var result = {};
//result.one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
//result.two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
if (result != null) {
$.ajax({
type: 'get',
url: "/Manage/CreateGroupRoleRestriction",
//url: '#Url.RouteUrl(new{ action= "CreateGroupRoleRestriction", controller= "Manage", one = "one", two = "two"})',,
data: { one, two },
//params: { one, two }
/*dataType: String,*/
//success: alert(result)
});
}
else {
alert("Error");
}
}
</script>
However, the issue is that the string values will not post to the Action Result, see below.
The values "one" and "two" are null.
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("/Manage/CreateGroupRoleRestriction?{one,two}")]
[ValidateAntiForgeryToken]
public ActionResult CreateGroupRoleRestriction(FormCollection formCollection, string message2, string one, string two)
{
UserDataBusinessLayer userDataBusinessLayer = new UserDataBusinessLayer();
userDataBusinessLayer.Restrict1(message2);
UserDataBusinessLayer userDataBusinessLayer2 = new UserDataBusinessLayer();
userDataBusinessLayer2.Restrict2();
try
{
UserData userData = new UserData();
TryUpdateModel(userData);
if (ModelState.IsValid)
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer3 = new UserDataBusinessLayer();
userDataBusinessLayer3.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
else
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer4 = new UserDataBusinessLayer();
userDataBusinessLayer4.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
}
catch (Exception ex)
{
Logger.Log(ex);
return RedirectToAction("CreateGroupRoleRestriction");
}
}
Please try changing 'type' in ajax to 'post'.
type: 'post'

send data from ajax to spring controller

var form_data = {
itemid: globalSourceItem.substr(globalSourceItem.indexOf("-") + 1),
columnName: jqInputs[0].value,
displayName: jqInputs[1].value,
format: jqInputs[2].value,
KBE: jqInputs[3].value,
dgroup: jqInputs[4].value,
dupkey: jqInputs[5].value ,
measurement: jqInputs[6].value ,
times: new Date().getTime()
};
// console.log(form_data);
// console.log($("#tourl").html());
$.ajax({
url: $("#tourl").html(),
type: 'POST',
datatype: 'json',
data: form_data,
success: function(message) {
var j_obj = $.parseJSON(message);
// console.log(j_obj);return false;
if (j_obj.hasOwnProperty('success')) {
toastr.info('Item updated successfully');
setTimeout(function(){
window.location.reload();
},1000);
} else {
toastr.info('There was a problem.');
}
},
error: function(xhr, textStatus, errorThrown)
{
toastr.info('There seems to be a network problem. Please try again in some time.');
}
});
}
Hii friends , this code is working for php and i need to send the same data to the spring mvc through the ajax , can anyone please help me with the exact solution where to make changes as Iam struckup with the same doubt for like 2 weeks...
public class TestController {
#RequestMapping(value = "url", method = RequestMethod.POST)
public ModelAndView action(#RequestBody FormData formData) {
...
}
}
public class FormData {
private String itemid;
public String getItemid() {
return itemid;
}
public void setItemid(String itemid) {
this.itemid = itemid;
}
//...
}
Try sth like this. You should be able to map JSON Object to Java Object.
Maybe you could use annotation #ResponseBody and convert JSONObject to String:
#RequestMapping(value = "/ajax", method = RequestMethod.POST, produces="application/json")
#ResponseBody
public String ajax(#RequestBody ListDataDefinition listDataDefinition) {
System.out.println("id="+listDataDefinition.getItemid());
int i=SchemaDAOI.updateldd(listDataDefinition);
String message="success";
JSONObject obj = new JSONObject();
try {
obj.put("success", "success");
}
catch (JSONException e) {
e.printStackTrace();
}
if(i==1){
System.out.println("success");
}
else{
System.out.println("failure");
}
return obj.toString();
}
}
If you send String to View as ResponseBody and set produces as JSON it should be treated as pure JSON RQ.

how to write hibernate spatial query?

This is homePage.jsp code :
<button id="bilgial" onclick="getVector(id)">Get Vector</button>
<input type="text" id="hs">
and this is getVector(id) function :
var id = document.getElementById("hs").value;
function getVector(id) {
ajax({
type: "GET",
path: "/getGeoJson",
data: {id: id},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data) {
var parser = new OpenLayers.Format.GeoJSON();
var feature = parser.read(data.data);
if (feature.length != 0) {
feature[0].attributes.id = data.id;
}
vectors.addFeatures(feature);
}
});
}
this is my controller get method :
#Controller
public class HSpatialController {
SavegeojsonManager add = new SavegeojsonManager();
#RequestMapping(value = "/getGeoJson", method = RequestMethod.GET)
#ResponseBody
public GeoJSON getGeoJson( final HttpServletRequest request,#RequestParam("id") final String vectorId) {
return add.get(vectorId);
}
}
and this is SavegeojsonManager class and get method :
public GeoJSON get(String id) {
GeoJSON geoJson = new GeoJSON();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("select e from SavegeojsonEntity ????")
query.setParameter("", ??);
return geoJson;
}
or how can I do otherwise ?
I want to was eat with the number that was in the database that you want to take the data from the TextBox equally with data GetData ?
So code should be like this:
public GeoJSON get(String id) {
GeoJSON geoJson = new GeoJSON();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("from SavegeojsonEntity s where s.id = :id")
query.setParameter("id", Integer.valueOf(id));
List entityList = query.getResultList();
if(entityList != null && !entityList.isEmpty()){
SavegeojsonEntity entity = (SavegeojsonEntity)entityList.get(0);
geoJson.setType(entity.getVectorType());
if(entity.getVectorType().equals("Point")){
geoJson.setData(entity.getPoint());//or entity.getXXX() since you need to get point data,
} else if(...){
//same for Polygon/MultiPolygon/StringLine and so on
}
}
em.getTransaction().close();
return geoJson;
}

View not rendering after foreach loop MVC

Goal: I am attempting to populate a table based on a dropdown list using Razor syntax to populate my table.
Summary: I am passing the model into my View and looping thru each object within my model. I am able to see the objects populated within the model when debugging the View, however, when the page actually displays, There is nothing in the table and the only thing that is displaying is the dropdown.
Question: What may be the problem with the page rendering?
My view is as follows:
#model IEnumerable<FantasySportsMVC.Models.PlayerDetails>
#{
ViewBag.Title = "Position";
}
<h2>Position</h2>
<body>
<div>
#Html.DropDownList("ddlTournaments",(IEnumerable<SelectListItem>)ViewBag.Tournaments, new { id="ddlTournament", name="ddlTournament"})
</div>
<div>
<input type="button" id="btnGetData" value="Show me some stuff, Yo!" />
</div>
<div id="results">
</div>
<table id="tbDetails">
#if(Model != null)
{
<tbody>
#foreach (var player in Model)
{
<tr>
<td>#player.LastName</td>
<td>#player.FirstName</td>
<td>#player.Position</td>
</tr>
}
</tbody>
}
</table>
</body>
<script type="text/javascript">
function SendTournamentId() {
var data = JSON.stringify({ id : $("#ddlTournament option:selected").val()});
$.ajax({
url: '/Leaderboard/Position',
type: 'POST',
dataType: 'json',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (result) {
//return JSON.stringify($("#ddlTournament option:selected").val());
$("#ddlTournament option:selected").val(result.d.id);
}
});
}
$(function () {
$('#btnGetData').click(SendTournamentId);
});
</script>
My Controller is as follows:
public class LeaderboardController : Controller
{
public ActionResult Position()
{
ViewBag.Tournaments = GetTournamentDetailsSelectList();
return View();
}
[HttpPost]
public ActionResult Position(string id)
{
ViewBag.Tournaments = GetTournamentDetailsSelectList();
var tournamentId = id;
var url = ConstructLeaderboardUrl(tournamentId);
var xmlToJsonUrl = ConvertXmltoJson(url);
List<PlayerDetails> details = BindDataTablePlayerDetails(xmlToJsonUrl);
return View(details);
}
}
private static List<PlayerDetails> BindDataTablePlayerDetails(string url)
{
dtAttributeList = new DataTable();
var details = new List<PlayerDetails>();
try
{
//ConvertXmltoJson(url);
// Construct Datatable
dtAttributeList.Columns.Add("Last Name", typeof(string));
dtAttributeList.Columns.Add("First Name", typeof(string));
dtAttributeList.Columns.Add("Position", typeof(string));
// Add rows to Datatable from Json
for (int i = 0; i < doc.GetElementsByTagName("player").Count; i++)
{
dtAttributeList.Rows.Add(
doc.GetElementsByTagName("player").Item(i).Attributes["last_name"].Value,
doc.GetElementsByTagName("player").Item(i).Attributes["first_name"].Value,
doc.GetElementsByTagName("player").Item(i).Attributes["position"].Value);
}
// Add rows from Datatable to PlayerDetails
foreach (DataRow row in dtAttributeList.Rows)
{
var player = new PlayerDetails();
player.LastName = row["Last Name"].ToString();
player.FirstName = row["First Name"].ToString();
player.Position = row["Position"].ToString();
details.Add(player);
}
}
catch (Exception e)
{
throw new Exception();
}
return details;
}

Auto complete is not working in my asp.net MVC

i have the following repository method to search for users containing a search parameter:-
public IEnumerable<User> searchusers2(string q)
{
return from u in entities1.Users
where (u.UserID.Contains(q) || string.IsNullOrEmpty(q))
select u;
}
which is called suing the following action method:-
public ActionResult QuickSearch(string term)
{
var users = r.searchusers2(term);
users.Select(a => new { value = a.UserID });
return Json(users, JsonRequestBehavior.AllowGet);
}
and on the view i have the following code:-
#using (Ajax.BeginForm("Search", "User", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "searchResults",
LoadingElementId = "progress"
}))
{
<input type="text" name="q" data-autocomplete-source="#Url.Action("QuickSearch", "User")" />
<input type="hidden" name="classid" value="#ViewBag.classid"/>
<input type="submit" value="Search" />
}
the above code is not working but if i change my action method to be as follow (without using a repository to perform the search) then the auto complete will work fine,,, so what might be causing this problem:-
public ActionResult QuickSearch(string term)
{
var users = entities1.Users
.Where(e => e.UserID.Contains(term))
.Select(r => new {value = r.UserID });
return Json(users, JsonRequestBehavior.AllowGet);
}
In the repository-version you're returning the whole User object in Json, The Select in
public ActionResult QuickSearch(string term)
{
var users = r.searchusers2(term);
users.Select(a => new { value = a.UserID });
return Json(users, JsonRequestBehavior.AllowGet);
}
is doing nothing because you're not storing the returned values, you'll either need to chain the call together, e.g:
public ActionResult QuickSearch(string term)
{
var users = r.searchusers2(term).Select(a => new { value = a.UserID });
return Json(users, JsonRequestBehavior.AllowGet);
}
or use a separate variable:
public ActionResult QuickSearch(string term)
{
var users = r.searchusers2(term);
var values = users.Select(a => new { value = a.UserID });
return Json(values, JsonRequestBehavior.AllowGet);
}

Resources