What is the best way avoid reload the jsp page? - liferay

enter image description hereHere is my jsp code
<portlet:renderURL var="rssSearchResult">
<portlet:param name="<%=CMD.ACTION%>"
value="<%=RenderKeys.FIND_CONTENT_SEARCH%>" />
<%-- <portlet:param name="categoryId" value="<%=String.valueOf(category.getCategoryId())%>"/> --%>
<div id="category-content" class="span8">
<aui:form render="<%=rssSearchResult %>">
<aui:input placeholder="Please Enter RSS Feed Title Here"
name="search" label="" id="searchTitle" type="text"
style="width:300px;" />
<aui:button type="button" name="search" id="searchTitle" value="submit" class="Find_content_search"
onclick="javascript:mynav('<%=rssSearchResult%>');addinMoveableBar();"></aui:button>
</aui:form>
*************Here is my java source code************
#RenderMapping(params=CMD.ACTION+StringPool.EQUAL+RenderKeys.FIND_CONTENT_SEARCH)
public void rssSearchResult(RenderRequest renderRequest,
RenderResponse renderResponse) {
String searchValue= ParamUtil.getString(renderRequest, "search");
DynamicQuery SearchaQuery = DynamicQueryFactoryUtil.forClass(
AssetEntry.class, PortletClassLoaderUtil.getClassLoader());
SearchaQuery.add(PropertyFactoryUtil.forName("title").eq(searchValue));
try {
List<AssetEntry> assentries=AssetEntryLocalServiceUtil.dynamicQuery(SearchaQuery);
List<AssetCategory> assetcategory=null;
for(AssetEntry assetentry:assentries){
assetcategory= AssetCategoryLocalServiceUtil.getAssetEntryAssetCategories(assetentry.getEntryId(), -1, -1);
}
renderRequest.setAttribute("AssetCategory", assetcategory);
renderRequest.setAttribute("AssetEntries", assentries);
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*************main.js***************
function mynav(navurl){
ajaxindicatorstart("Processing Please Wait");
loadPage(navurl);
history.pushState({}, '', navurl);
}
I have a search text box with submit button if i search title of category it has to be display without reloading the page....

Related

Not able to get the value of the button in my controller after postback in MVC5

I am trying to capture the value of the button in my controller method. I have two buttons save and submit which post back the same form. I need to identify which button was pressed. The buttons are physically present outside the form and use javascript to trigger a postback. The reason why the buttons are out is because of layout reason. I have named the buttons as well as assigned values. Not sure why they are null on postback. Here is the code
<div class="buttonalign" >
<button name="button" value="submit" onclick="$('#requestHeaderform').submit();" class="btn btn-primary">Submit</button>
<button name="button" value="save" onclick="$('#requestHeaderform').submit();" class="btn btn-default">Save as draft</button>
</div>
#using (Html.BeginForm("Request_Insert", "Request", FormMethod.Post,new { id = "requestHeaderform" }))
{
<div class="newRequestHeader">
#Html.Partial("~/Views/Request/_RequestHeaderView.cshtml")
</div>
}
Controller method
[HttpPost]
public ActionResult Request_Insert(NewRequestViewModel newReqeustViewModel,string button)
{
switch (button)
{
case "submit":
// Do something
break;
case "save":
// Do something
break;
default:
break;
}
}
**View**
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function() {
$("#submit").click(function(e) {
e.preventDefault();
alert($("#submit").attr("value"));
$('#ButtonHiddenValue').val($("#submit").attr("value"));
$('#requestHeaderform').submit();
});
$("#save").click(function(e) {
e.preventDefault();
$('#ButtonHiddenValue').val($("#save").attr("value"));
$('#requestHeaderform').submit();
});
});
</script>
<div class="row">
<div class="buttonalign" >
<button name="button" id="submit" value="submit" class="btn btn-primary">Submit</button>
<button name="button" id="save" value="save" class="btn btn-default">Save as draft</button>
</div>
#using (Html.BeginForm("Request_Insert", "Home", FormMethod.Post,new { id = "requestHeaderform" }))
{
<input id="ButtonHiddenValue" name="ButtonHiddenValue" type="hidden" />
}
</div>
**Controller**
public ActionResult Request_Insert(NewRequestViewModel newReqeustViewModel)
{
return null;
}
**Model**
public class NewRequestViewModel
{
public string ButtonHiddenValue { get; set; }
}

Restore the active bootstrap tab after postback when page has multiple forms

I have an ASP.Net MVC 5 project that has a page with 2 bootstrap tabs. Each tab has two forms for a total of 4 forms on the page. My viewmodel has a superset of all the fields in the 4 forms.
When I post a form, I want the response view to display the same tab that was showing when the form was posted. This SO answer Remain bootstrap tab after postback c# indicates that I should set the active tab in a hidden field, return it in the view model, then restore it on postback.
This SO answer asp.net MVC 4 multiple post via different forms indicates that returned fields must be within the form I'm returning. This presents a problem since the hidden field needs to be in the scope of all the forms.
On postback, how do I display the same tab that was showing when the form was posted when I have multiple forms on the page?
I solved this problem by removing the 4 forms and replacing it with a single form that spanned the previous 4. To get the form to post-back to the proper controller/action, I wrote some javascript that is invoked when one of the 4 submit buttons is activated.
It sets the new form's action to the appropriate controller/action and then submits the form. This way, there is only 1 form and 1 hidden field to hold the active tab and the correct action still gets invoked on post-back. A test program with 2 tabs and (for simplicity) only 2 actions is here:
View:
#model MultiPostDestinations.Models.HomeVM
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br/><br /><br /><br />
<div class="row">
<div class="col-md-4">
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post, new { id = "submitForm", enctype = "multipart/form-data" })) {
#Html.HiddenFor(m => m.ActiveTab)
<div id="Tabs" role="tabpanel" class="container" style="width: 1000px">
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li class="active">Details</li>
<li>Historic Model Analysis</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div id="details" role="tabpanel" class="tab-pane fade in active">
<h2>Details Tab</h2>
<h4>label: #Model.F1</h4><br /><br />
#Html.DisplayFor(m => m.F1)<br /><br />
#Html.EditorFor(m => m.F1)<br /><br />
#Html.ActionLink("ActionLink Submit form", "SubmitGet", "Home", new { #class = "btn btn-default" })<br /><br />
<input type="submit" value="input SubmitForm" class="btn btn-default" /><br /><br />
<input id="submitButton1" type="button" value="javascript input to /Home/Submit1" class="btn btn-default" /><br /><br />
</div>
<div id="history" role="tabpanel" class="tab-pane fade">
<h2>Historic Model Analysis tab</h2>
<h4>label: #Model.F2</h4><br /><br />
#Html.DisplayFor(m => m.F2)<br /><br />
#Html.EditorFor(m => m.F2)<br /><br />
<input type="submit" value="input SubmitForm" class="btn btn-default" /><br /><br />
<input id="submitButton2" type="button" value="javascript input to /Home/Submit2" class="btn btn-default" /><br /><br />
</div>
</div>
</div>
}
</div>
</div>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$('#submitButton1').click(function (e) {
e.preventDefault(); // recommended in SO, does not appear to be required
$('#submitForm').attr('action', '/Home/Submit1');
$('#submitForm').submit();
});
$('#submitButton2').click(function (e) {
e.preventDefault(); // recommended in SO, does not appear to be required
$('#submitForm').attr('action', '/Home/Submit2');
$('#submitForm').submit(); // previous doesn't work - why?
});
var lastActiveTab = ($('#ActiveTab').val() !== '') ? $('#ActiveTab').val() : 'details';
$('#Tabs a[href="#' + lastActiveTab + '"]').tab('show');
$("#Tabs a").click(function () {
$('#ActiveTab').val($(this).attr("href").replace("#", ""));
});
});
</script>
}
Here is the Controller with 2 actions:
using MultiPostDestinations.Models;
using System.Web.Mvc;
namespace MultiPostDestinations.Controllers {
public class HomeController : Controller {
public ActionResult Index() {
var vm = new HomeVM() { F1 = "Index-F1", F2 = "Index-F2", ActiveTab = "" };
return View("Index", vm);
}
[HttpPost]
public ActionResult Submit1(HomeVM vm) {
System.Diagnostics.Debug.WriteLine("HomeVM.Submit1: F1={0}, F2={1}", vm.F1 ?? string.Empty, vm.F2 ?? string.Empty);
// ModelState.Clear(); // uncomment if you want Html.EditorFor() fields to update on postback
return View("Index", vm);
}
[HttpPost]
public ActionResult Submit2(HomeVM vm) {
System.Diagnostics.Debug.WriteLine("HomeVM.Submit2: F1={0}, F2={1}", vm.F1 ?? string.Empty, vm.F2 ?? string.Empty);
//ModelState.Clear(); // uncomment if you want Html.EditorFor() fields to update on postback
return View("Index", vm);
}
}
}
And finally the view-model:
namespace MultiPostDestinations.Models {
public class HomeVM {
public string ActiveTab { get; set; }
public string F1 { get; set; }
public string F2 { get; set; }
}
}

Render()'s Method different reactions

I have my render() method with no code.
And I have this action-method:
#ProcessAction(name = "viewBook")
public void viewBook(ActionRequest actionRequest,ActionResponse actionResponse) throws SystemException, PortalException {
long bookId = ParamUtil.getLong(actionRequest, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
actionRequest.setAttribute(FinalStrings.BOOK_ENTRY, book);
actionResponse.setRenderParameter("jspPage", "/html/LibraryPortlet/view_book.jsp");
How can I rewrite this "GET" method into render() method? I mean I need to run
public void render(RenderRequest renderRequest, RenderResponse rendeResponse){
super.render(renderRequest, renderResponse)
}
in the default situation and
public void render(RenderRequest renderRequest, RenderResponse rendeResponse){
\\THIS CODE IS NOT WORKING, IT'S JUST TO SHOW WHAT I WANT!
long bookId = ParamUtil.getLong(actionRequest, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
actionRequest.setAttribute(FinalStrings.BOOK_ENTRY, book);
actionResponse.setRenderParameter("jspPage", "/html/LibraryPortlet/view_book.jsp");
when I need to use viewBook() method. How can I parametrize(?) render() method?
Update:
For more details I attached one screenshot:
Meanwhile in my action.jsp:
<liferay-ui:icon-menu>
<portlet:actionURL name="deleteBook" var="deleteURL">
<portlet:param name="bookId"
value="${String.valueOf(book.getBookId())}" />
</portlet:actionURL>
<portlet:renderURL name="viewBook" var="viewURL">
<portlet:param name="bookId"
value="${String.valueOf(book.getBookId())}" />
</portlet:renderURL>
<portlet:renderURL var="editBookURL" name="viewEdit">
<portlet:param name="bookId" value="${String.valueOf(book.getBookId())}" />
</portlet:renderURL>
<liferay-ui:icon image="add" message="View" url="${viewURL.toString()}" />
<liferay-ui:icon image="add" message="Edit" url="${editBookURL.toString()}" />
<liferay-ui:icon-delete image="delete" message="Delete" url="${deleteURL.toString()}" />
In my view_book.jsp:
<%#page import="com.softwerke.FinalStrings"%>
<%#page import="com.softwerke.model.Book"%>
<%#page import="com.softwerke.service.BookLocalServiceUtil"%>
<%#page import="com.liferay.portal.kernel.util.ParamUtil"%>
<%# include file="/html/init.jsp"%>
<portlet:renderURL var="backURL">
<portlet:param name="jspPage" value="/html/view.jsp"/>
</portlet:renderURL>
<liferay-ui:header backURL="${backURL}" title="Back" />
<%
Book book = (Book) request.getAttribute(FinalStrings.BOOK_ENTRY);
%>
<aui:form>
<aui:model-context bean="${book}" model="${Book.class}" />
<aui:input name="bookName" label="Book Name" disabled="true"/>
<aui:input type="textarea" name="description" label="Description" disabled="true"/>
<aui:input name="authorName" label="Author Name" disabled="true"/>
<aui:input name="price" label="Price" disabled="true"/>
</aui:form>
According to my task I can not use Action URL here. What should I do???
You can send a command param to the render, so you can split the logic into two or more render methods, depending on the command, or maybe easier, invoke a mvcPath without the need of implementing anything in render(). Include something like this in the jsp with your list of books:
<portlet:renderURL var="myBookURL">
<portlet:param name="mvcPath" value="/view_book.jsp" />
<portlet:param name="bookId" value="<%= someBookId %>" />
</portlet:renderURL>
View My Book
You just need a view_book.jsp with something like:
<%
long bookId = ParamUtil.getLong(request, "bookId");
Book book = BookLocalServiceUtil.getBook(bookId);
%>
Hope it helps.

Liferay: How to place values (or not lose values) in ParamUtil in case of exception?

I am new to developing on Liferay and am currently using Liferay 6.2 on Eclipse Kepler IDE.
I am currently making a small webpage based on the following view & add/update example in the development guide
In the example the method paramUtil.getLong(long) is used to pass the id of the row to be updated to the add/update page.
My issue is that when an exception occurs (on the back end) this data is lost and the page changes to an add entry page.
How do I retain the data sot that ParamUtil can retrieve it when an exception is thrown on the back end?
I have included snippets of the example front end code below.
VIEW.JSP:
<liferay-ui:search-container-row
className="com.nosester.portlet.eventlisting.model.Location"
keyProperty="locationId"
modelVar="location" escapedModel="<%= true %>"
>
<liferay-ui:search-container-column-text
name="name"
value="<%= location.getName() %>"
/>
<liferay-ui:search-container-column-text
name="description"
value="<%= location.getDescription() %>"
/>
<liferay-ui:search-container-column-text
name="streetAddress"
value="<%= location.getStreetAddress() %>"
/>
<liferay-ui:search-container-column-text
name="city"
value="<%= location.getCity() %>"
/>
<liferay-ui:search-container-column-text
name="stateOrProvince"
value="<%= location.getStateOrProvince() %>"
/>
<liferay-ui:search-container-column-text
name="country"
value="<%= location.getCountry() %>"
/>
<liferay-ui:search-container-column-jsp
align="right"
path="/html/locationlisting/location_actions.jsp"
/>
</liferay-ui:search-container-row>
<liferay-ui:search-iterator />
ACTIONS.JSP
<%
ResultRow row = (ResultRow) request
.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
Location location = (Location) row.getObject();
long groupId = location.getGroupId();
String name = Location.class.getName();
long locationId = location.getLocationId();
String redirect = PortalUtil.getCurrentURL(renderRequest);
%>
<liferay-ui:icon-menu>
<portlet:renderURL var="editURL">
<portlet:param name="mvcPath" value="/html/locationlisting/edit_location.jsp" />
<portlet:param name="locationId" value="<%= String.valueOf(locationId) %>" />
<portlet:param name="redirect" value="<%= redirect %>" />
</portlet:renderURL>
<liferay-ui:icon image="edit" url="<%= editURL.toString() %>" />
EDIT.JSP
<%
Location location = null;
long locationId = ParamUtil.getLong(request, "locationId");
if (locationId > 0) {
location = LocationLocalServiceUtil.getLocation(locationId);
}
String redirect = ParamUtil.getString(request, "redirect");
%>
<aui:model-context bean="<%= location %>" model="<%= Location.class %>" />
<portlet:renderURL var="viewLocationURL" />
<portlet:actionURL name='<%= location == null ? "addLocation" : "updateLocation" %>' var="editLocationURL" windowState="normal" />
<liferay-ui:header
backURL="<%= viewLocationURL %>"
title='<%= (location != null) ? location.getName() : "New Location" %>'
/>
<aui:form action="<%= editLocationURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input name="redirect" type="hidden" value="<%= redirect %>" />
<aui:input name="locationId" type="hidden" value='<%= location == null ? "" : location.getLocationId() %>'/>
<aui:input name="name" />
<aui:input name="description" />
<aui:input name="streetAddress" />
<aui:input name="city" />
<aui:input name="stateOrProvince" />
<aui:input name="country" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button onClick="<%= viewLocationURL %>" type="cancel" />
</aui:button-row>
UPDATE 1:
Adding back end logic as requested by Parkash Kumar:
LocationListingPortlet.java (Link to Example from Document)
public void updateLocation(ActionRequest request, ActionResponse response)
throws Exception {
_updateLocation(request);
sendRedirect(request, response);
}
private Location _updateLocation(ActionRequest request)
throws PortalException, SystemException {
long locationId = (ParamUtil.getLong(request, "locationId"));
String name = (ParamUtil.getString(request, "name"));
String description = (ParamUtil.getString(request, "description"));
String streetAddress = (ParamUtil.getString(request, "streetAddress"));
String city = (ParamUtil.getString(request, "city"));
String stateOrProvince = (ParamUtil.getString(request, "stateOrProvince"));
String country = (ParamUtil.getString(request, "country"));
ServiceContext serviceContext = ServiceContextFactory.getInstance(
Location.class.getName(), request);
Location location = null;
if (locationId <= 0) {
location = LocationLocalServiceUtil.addLocation(
serviceContext.getUserId(), serviceContext.getScopeGroupId(), name, description,
streetAddress, city, stateOrProvince, country, serviceContext);
}
else {
location = LocationLocalServiceUtil.getLocation(locationId);
location = LocationLocalServiceUtil.updateLocation(
serviceContext.getUserId(), locationId, name,
description, streetAddress, city, stateOrProvince, country,
serviceContext);
}
return location;
}
private static Log _log = LogFactoryUtil.getLog(LocationListingPortlet.class);
}
In-case exception occurs, handle it in _updateLocation and reset required parameters in catch, as following:
Location location = null;
try {
if (locationId <= 0) {
location = LocationLocalServiceUtil.addLocation(
serviceContext.getUserId(), serviceContext.getScopeGroupId(),
name, description, streetAddress, city, stateOrProvince,
country, serviceContext);
} else {
location = LocationLocalServiceUtil.getLocation(locationId);
location = LocationLocalServiceUtil.updateLocation(
serviceContext.getUserId(), locationId, name,
description, streetAddress, city, stateOrProvince, country,
serviceContext);
}
}catch(Exception ex){
_log.error(ex);
// set render parameters
request.setRenderParameter("locationId", locationId);
}

Passing parameters to Liferay PortletURL

I would like to validate the request of an user by doing he types his personal key. First of all he does the request, now the portlet redirects to a second jsp file where he validates with the key and finally if it is ok the portlet complete the request otherwise returns to the first step.
Here is the code,
1.- view.jsp (the request)
<%# include file="/html/blue/init.jsp" %>
Welcome to our Colors workflow
<br/>
<%
PortletURL redirectURL = renderResponse.createActionURL();
redirectURL.setParameter(ActionRequest.ACTION_NAME, "redirect");
%>
<aui:form name="fmAdd" method="POST" action="<%= redirectURL.toString() %>">
<aui:input type="hidden" name="myaction" value="add" />
<aui:button type="submit" value="Add New Box"/>
</aui:form>
<aui:form name="fmList" method="POST" action="<%= redirectURL.toString() %>">
<aui:input type="hidden" name="myaction" value="list" />
<aui:button type="submit" value="Show All Boxes"/>
</aui:form>
2.- the java code,
public void redirect(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
String action = ParamUtil.getString(actionRequest, "myaction");
PortletURL redirectURL = null;
String redirectJSP = "/checkuser.jsp";
if(action != null) {
String portletName = (String)actionRequest.getAttribute(WebKeys.PORTLET_ID);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
redirectURL = PortletURLFactoryUtil.create(PortalUtil.getHttpServletRequest(actionRequest),
portletName, themeDisplay.getLayout().getPlid(), PortletRequest.RENDER_PHASE);
redirectURL.setParameter("myaction", action);
redirectURL.setParameter("jspPage", redirectJSP);
}
actionResponse.sendRedirect(redirectURL.toString());
}
3._ checkuser.jsp (the user validate with his key)
<%# include file="/html/blue/init.jsp" %>
<%
PortletURL checkUserURL = renderResponse.createActionURL();
checkUserURL.setParameter(ActionRequest.ACTION_NAME, "checkUser");
String myaction = renderRequest.getParameter("myaction");
%>
<p> Your action: <%= myaction %> </p>
<aui:form name="fm" method="POST" action="<%= checkUserURL.toString() %>">
<aui:input type="hidden" name="myaction" value="<%= myaction %>" />
<aui:input type="text" name="key" value=""/>
<aui:button type="submit" value="Save"/>
</aui:form>
In this phase I am getting the first problem because I do not see the value of the request (myaction variable). This is only for debug.
4._ the java code that catches the last form,
public void checkUser(ActionRequest actionRequest,
ActionResponse actionResponse) throws IOException, PortletException {
String key = ParamUtil.getString(actionRequest, "key");
String action = ParamUtil.getString(actionRequest, "myaction");
String portletName = (String)actionRequest.getAttribute(WebKeys.PORTLET_ID);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
PortletURL redirectURL = PortletURLFactoryUtil.create(PortalUtil.getHttpServletRequest(actionRequest),
portletName, themeDisplay.getLayout().getPlid(), PortletRequest.RENDER_PHASE);
String redirectJSP = "/view.jsp";
if(key != null) {
if(key.equalsIgnoreCase("blue")) {
if(action != null) {
if(action.equalsIgnoreCase("add")) {
redirectJSP = "/update.jsp";
}
if(action.equalsIgnoreCase("list")) {
redirectJSP = "/list.jsp";
}
}
}
}
redirectURL.setParameter("jspPage", redirectJSP);
actionResponse.sendRedirect(redirectURL.toString());
}
In this phase the portlet always goes to view.jsp where the user does the request. I am thinking both key and action variables are null or at least one of them.
What am I doing wrong?
Regards,
Jose
In Liferay, the parameters are set with a namespace so that they don't cause problems when there are more than 1 portlet on the page. Especially if you have the exact same portlet on the page twice! So when you're setting myaction, it really gets set to something like _myportlet_INSTANCE_xlka_myaction or something similar.
You can use com.liferay.portal.kernel.util.ParamUtil to help you get your parameters without having to worry about the scoping. For example:
ParamUtil.getString(request, "myaction");

Resources