Struts2 action not being called on page refresh - javascript

I'm making a CRUD application for a school project, where there is a list of 'lesson groups', which you can add or remove.
I have a bootstrap modal that looks like this, where you can input a lesson group name and press a button to submit it:
<div class="modal fade" id="lessonGroupAddModal" tabindex="-1" role="dialog"
aria-labelledby="lessonGroupAddModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="lessonGroupAddModalLabel">Les groep toevoegen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="addLessonGroupForm" role="form">
<div class="form-group">
<label for="lessonGroupName-input" class="col-2 col-form-label">Naam</label>
<div class="col-10">
<input class="form-control" type="text" value="" id="lessonGroupName-input">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Sluiten</button>
<button id="addLessonGroupButton" type="button" class="btn btn-primary">Toevoegen</button>
</div>
</div>
</div>
</div>
The button works by a JavaScript AJAX post request, this looks like this:
$("#addLessonGroupButton").on("click", function() {
if($("input[type=text]#lessonGroupName-input").val()) {
$.ajax({
type: 'POST',
url:'lessongroup/add.action',
dataType: 'json',
data : "lessonGroupName="+$("input[type=text]#lessonGroupName-input").val(),
});
}
location.reload();
});
The action method i'm using for this looks like this:
public String addLessonGroup() {
if (this.lessonGroupName == null || this.lessonGroupName.equals("")) {
return ERROR;
}
LessonGroup previousLessonGroup = this.getLessonGroups().last();
TestDAOLessonGroup.getInstance().create(new LessonGroup(previousLessonGroup.getId() + 1, lessonGroupName));
System.out.println("added lesson group with name " + lessonGroupName);
return SUCCESS;
}
The TestDAOLessonGroup is a singleton which saves that objects, i'm 100% sure the object is only getting made once.
The execute method of the controller looks like this:
public String execute() {
if (lessonGroups == null) {
lessonGroups = new TreeSet<>();
}
lessonGroups.clear();
lessonGroups.addAll(TestDAOLessonGroup.getInstance().getLessongroups());
return SUCCESS;
}
This puts the most recent lesson groups into the variable, which i am getting in the view.
My struts.xml action mapping looks like this:
<action name="lessongroup" class="employeemanagement.LessonGroupListingAction"
method="execute">
<result name="success">index.jsp</result>
</action>
I'm 100% sure this mapping works, and the lesson grouups are getting loaded in the view.
The problem is that when you add a new lesson group to the DAO via the post request, and it reloads the page by the location.reload(); statement, it doesn't call up the action the first time. When I add another lesson group, it works just fine.
How can I make it so that the Action would get called on the first page refresh? Am I using the right approach for this?

The url is not mapped to the action. You should add
<action name="add" class="employeemanagement.LessonGroupListingAction"
method="add">
<result type="json"/>
</action>
The json plugin is required to return json type result.
This action should be mapped to the url in ajax call
$("#addLessonGroupButton").on("click", function() {
if($("input[type=text]#lessonGroupName-input").val()) {
$.ajax({
type: 'POST',
url:'add.action',
dataType: 'json',
data : "lessonGroupName="+$("input[type=text]#lessonGroupName-input").val(),
success: function(data) {
console.log(JSON.stringify(data));
}
});
}
});

Related

How to pass a parameter to a modal form using Ajax

I have a razor page that displays a list of expenses for the Report selected. I have an "Add Expense" button on the page that brings up a modal. The modal is a partial View of the form. What i need to do is pass the ExpenseId to the modal. I can get the Id from the url like this
#{ var expenseId = Request.Url.Segments[3]; }
the button currently looks like this
<button type="button" data-toggle="modal" data-target="#expenseModal_#expenseId" data-id="#expenseId" class="btn btn-primary" id="addExpenses">
Add Expense
</button>
There are a few things in this that i do not know if i even need them. I was trying different things.
Modal
<!-- MODAL -->
<div class="modal fade" id="expenseModal_#expenseId" tabindex="-1" role="dialog" aria-labelledby="expenseModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="expenseModalLabel"> Expences </h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> <!-- MODEL HEADER-->
<div class="modal-body">
</div> <!-- MODAL BODY-->
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#addExpenses").click(function () {
$(".modal-body").html('');
$.ajax({
type: 'GET',
url: '#Url.Action("_ExpenseForm", "Admin")',
data: { type: $(this).attr("data-type") },
success: function (response) {
$(".modal-body").html(response);
$("#expenseModal").modal('show');
},
error: function () {
alert("Something went wrong");
}
});
});
});
</script>
The expense Id has to be inserted in the form so that when it is saved it saves it to the correct Expense report.
Controller actions
ExpensesDataAcessLayer objexpense = new ExpensesDataAcessLayer();
public ActionResult ExpenseReports()
{
return View(db.ExpenseReports.ToList());
}
public ActionResult Expenses(int ExpenseId)
{
return View(db.Expenses.Where(x => x.ExpenseId == ExpenseId).ToList());
}
public ActionResult _ExpenseForm()
{
CustomerEntities customerEntities = new CustomerEntities();
List<SelectListItem> categoryItem = new List<SelectListItem>();
ExpensesViewModel casModel = new ExpensesViewModel();
List<ExpenseTypes> expensetypes = customerEntities.ExpenseType.ToList();
expensetypes.ForEach(x =>
{
categoryItem.Add(new SelectListItem { Text = x.CategoryItem, Value = x.ItemCategoryId.ToString() });
});
casModel.ExpenseTypes = categoryItem;
return View(casModel);
}
Thanks for your help!
You can store expenseId into hidden field, like this
<input id="expenseId" name="expenseId" type="hidden" value="#Request.Url.Segments[3]">
Then you can get like this
$("#addExpenses").click(function () {
var expenseId = $("#expenseId").val();
// after code here
Updated
You can get expenseId like this
var expenseId = $(this).attr("data-id")
Then you can assign it to hidden field or anywhere in Model, Like this
<!-adding aditional input into HTML in MODEL-!>
<input id="expenseId" name="expenseId" type="hidden" value="">
<!- Javascript-!>
var expenseId = $(this).attr("data-id")
expenseId.val(expenseId );

modal iteration in foreach loop using ajax

I got a problem with foreach loop. What am i trying to do is get data (JsonResult) from action in controller. Get get songs for each album.
public JsonResult SongListByAlbum(int albumID)
{
var songs = (from song in Song.GetSongList()
join album in Album.GetAlbumList()
on song.AlbumID equals album.AlbumID
where (albumID == album.AlbumID)
select song).ToList();
return Json(songs,JsonRequestBehavior.AllowGet);
}
Then put them into view, for album get list of songs and show them as modals
There is my view:
#foreach (var item in Model.Albums){
<button id="#item.AlbumID" type="button" class="btn btn-primary myModals" data-toggle="modal" data-target="#exampleModal-#item.AlbumID">
Show
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal-#item.AlbumID" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-#item.AlbumID" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel-#item.AlbumID">#item.AlbumName #item.Year, #item.BandName</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="parent" class="modal-body">
</div>
<div class="modal-footer">
<button id="closeModal"type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
}
And there is a script, where I get songs for each album.
<script>
$(".myModals").on("click", function () {
var Id = $(this).attr('id');
alert(Id);
$.ajax({
type: "GET",
url: '#Url.RouteUrl(new{ action= "SongListByAlbum", controller="Default"})',
data: {albumID:Id},
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
for (var i in result) {
$('#parent').append('<p class="toRemove">' + result[i].SongName + '</p>');
}
},
error: function (response) {
alert('error');
}
});
});
</script>
The problem is : when i click on the first modal button everything is fine, i get what i want to. But when i click on the second one i got empty modal. Then when i click again on the first one i got data from previous click and penultimate. Image: enter image description here
To avoid multiple <div id="parent"> elements, you should probably assign the Id the same way you do for the buttons. Like <div id="parent-#item.AlbumID">. Then in your ajax call reference the correct div. $('#parent-' + Id).
Not sure if that is your only probably, but might get you closer.

Google Maps autocomplete in Bootstrap modal with Vue.js

I have Boostrap modal with <input>. I have implemented Google autocomplete for it with the following well-known trick:
.pac-container {
z-index: 10000 !important;
}
Now I'm struggling to make autocomplete working inside 2nd layer Boostrap Modal. Unfortunately, the z-index trick doesn't work here.
<div class="modal fade" id="editItemModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div id="editItem" class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Update Address <b>{{selectedItem.properties.NAME}}</b>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label class="sr-only" for="editItem_ADRESS1"></label>
<input v-model="selectedItem.properties.ADRESS1" type="text" class="form-control" id="editItem_ADRESS1" ref="editItem_ADRESS1" placeholder="{{selectedItem.properties.ADRESS1}}">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-success btn-ok" #click="save_item()" data-dismiss="modal">Save</a>
</div>
</div>
</div>
</div>
Then comes the Vue object
const editItem = new Vue({
el: "#editItem",
data: {
items: null,
selectedItem: null,
},
methods: {
save_item() {
this.selectedItem = itemsList.selectedItem;
var ip = location.host;
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://' + ip + '/updateItem',
data: {
command: "edit_item",
item_id: this.selectedItem.id,
adress1: this.selectedItem.properties.ADRESS1
},
success: function (responseData) {
if (responseData.result === false) {
console.log(responseData.result);
}
else {
console.log("successfully updated");
}
},
error: function (error) {
console.log('error', error);
}
}); // end of ajax
} // end od save_item()
} // end of methods
});
Finally, I was able to figure out what was the issue. It turns out that the DOM object is not created yet by Vue when the Google iniAutocomplete() function sets listeners.
In addition, my <input> didn't run the Google geolocate() function. That's how the <input> looks now:
<div class="form-group">
<label class="sr-only" for="edit-item_ADRESS1"></label>
<input id="edit-item_ADRESS1" v-model="selectedItem.properties.ADRESS1" type="text" class="form-control" onFocus="geolocate('edit-item')">
</div>
The next step was to make a minor change in the geolocate() function. I pass action variable onFocus event and use it to determine what DOM object initiated the call.
if (action == "add-item") {
autocomplete_add_item.setBounds(circle.getBounds());
}
if (action == "edit-item") {
// we need to run iniAutocomplete again after the DOM object was finally created by Vue
initAutocomplete();
autocomplete_edit_item.setBounds(circle.getBounds());
}

Get form values and pass it to Bootstrap modal on Submit

I'm trying to get my form data and pass it as JSON to my modal dialog, which also should open on Submit button!
Here is what I've done so far:
HTML
<form class="form-horizontal" id="configuration-form">
--unimportant--
<button type="submit" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#myModal">Submit</button>
</form>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Please copy this code to your HTML</h4>
</div>
<div class="modal-body">
<code id="configurationObject"></code><br/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS
(function(formId) {
$("#" + formId).submit(function(event){
event.preventDefault();
var errMsg = "Something went wrong with form submit, please try again";
var json = convertFormToJSON(this); //here I got my json object with all my form data
$.ajax({
type : 'POST',
data: {conf: JSON.stringify(json)},
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(data){
$("#configurationObject").html(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
return false;
});
})("configuration-form");
After Submit button is clicked I do get my JSON object with form data (I can log it after
var json = convertFormToJSON(this)
and my modal dialog window is opened, but I do miss my data aka.
element with id="configurationObject" is empty.
Thanks in advance
Have you tried to append() the data to #configurationObject rather than using html()?
According to documentation $.html() accepts A string of HTML to set as the content of each matched element. .
Here you are passing json data instead of string. So first, you have to convert json response to string. $("#configurationObject").html(JSON.stringify(data));
or you can use
$("#configurationObject").append(data);

Using Bootstrap Modal window as PartialView

I was looking to using the Twitter Bootstrap Modal windows as a partial view. However, I do not really think that it was designed to be used in this fashion; it seems like it was meant to be used in a fairly static fashion. Nevertheless, I think it'd be cool to be able to use it as a partial view.
So for example, let's say I have a list of Games. Upon clicking on a link for a given game, I'd like to request data from the server and then display information about that game in a modal window "over the top of" the present page.
I've done a little bit of research and found this post which is similar but not quite the same.
Has anyone tried this with success or failure? Anyone have something on jsFiddle or some source they'd be willing to share?
Thanks for your help.
Yes we have done this.
In your Index.cshtml you'll have something like..
<div id='gameModal' class='modal hide fade in' data-url='#Url.Action("GetGameListing")'>
<div id='gameContainer'>
</div>
</div>
<button id='showGame'>Show Game Listing</button>
Then in JS for the same page (inlined or in a separate file you'll have something like this..
$(document).ready(function() {
$('#showGame').click(function() {
var url = $('#gameModal').data('url');
$.get(url, function(data) {
$('#gameContainer').html(data);
$('#gameModal').modal('show');
});
});
});
With a method on your controller that looks like this..
[HttpGet]
public ActionResult GetGameListing()
{
var model = // do whatever you need to get your model
return PartialView(model);
}
You will of course need a view called GetGameListing.cshtml inside of your Views folder..
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate">
<%Html.RenderPartial("Modal");%>
</script>
...which lets me keep my templates in a partial view called Modal.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{Name}}</h3>
</div>
<div class="modal-body">
<table class="table table-striped table-condensed">
<tbody>
<tr><td>ID</td><td>{{Id}}</td></tr>
<tr><td>Name</td><td>{{Name}}</td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%>
<div data-id="<%=Html.Encode(item.Id)%>"
id="modelModal<%=Html.Encode(item.Id)%>"
class="modal hide fade">
</div>
<%}%>
...and make ajax calls with jQuery:
<script type="text/javascript">
var modalTemplate = $("#modalTemplate").html()
$(".modal[data-id]").each(function() {
var $this = $(this)
var id = $this.attr("data-id")
$this.on("show", function() {
if ($this.html()) return
$.ajax({
type: "POST",
url: "<%=Url.Action("SomeAction")%>",
data: { id: id },
success: function(data) {
$this.append(Mustache.to_html(modalTemplate, data))
}
})
})
})
</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%>
<a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
<%=Html.Encode(item.DutModel.Name)%>
</a>
<%}%>
I have achieved this by using one nice example i have found here.
I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.
Complete and clear example project
http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals
It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call #{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '#Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
Put the modal and javascript into the partial view. Then call the partial view in your page.
This will handle form submission too.
Partial View
<div id="confirmDialog" class="modal fade" data-backdrop="false">
<div class="modal-dialog" data-backdrop="false">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Missing Service Order</h4>
</div>
<div class="modal-body">
<p>You have not entered a Service Order. Do you want to continue?</p>
</div>
<div class="modal-footer">
<input id="btnSubmit" type="submit" class="btn btn-primary"
value="Submit" href="javascript:"
onClick="document.getElementById('Coordinate').submit()" />
<button type="button" class="btn btn-default" data-
dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Javascript
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#Coordinate").on('submit',
function (e) {
if ($("#ServiceOrder").val() == '') {
e.preventDefault();
$('#confirmDialog').modal('show');
}
});
});
</script>
Then just call your partial inside the form of your page.
Create.cshtml
#using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
{
//Form Code
#Html.Partial("ConfirmDialog")
}

Categories

Resources