I am new to Liferay , i am unable to navigate through Pages using renderURL , please tell me where i am doing a mistake
I am struck here , i am not able to navigate to the Second Page during on click of an hyper link as shown below
This is my First Page , where i am showing the First Page ( view.jsp ) , But from view.jsp , i am unable to show view2.jsp
public class TestPortlet extends GenericPortlet {
public void doView(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
renderResponse.setContentType("text/html");
PortletRequestDispatcher rd = getPortletConfig().getPortletContext()
.getRequestDispatcher("/html/test/view.jsp");
if (rd != null) {
rd.include(renderRequest, renderResponse);
}
}
}
This is my view.jsp
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
This is the <b>Sai Test Portlet</b> portlet in View mode.
<portlet:renderURL var="clickRenderURL">
<portlet:param name="jspPage" value="/html/test/view2.jsp" />
</portlet:renderURL>
Click here
This is my view2.jsp
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
This is the <b>View 2 </b> portlet in View mode.
There are no errros in console mode , and i am uisng Liferay 6.1 version .
Can you check the same using
"liferay-portlet:renderURL" tag.
Instead of using "portlet:renderURL" tag.
Rest all looks fine to me.
Related
We implemented a corejsphook module to customize user_action.jsp in Liferay 7.0.6, which worked fine.
After upgrading to Liferay 7.3.6 it stopped working. I have made sure the module that we are replacing the jsp into is correct by searching for it in the gogo shell. I also looked at the source code to confirm the package that contains the .jsp is right. And I updated the version number to the Liferay 7.3 bundle version (5.0.53). The entry in my bnd.bnd is:
Fragment-Host: com.liferay.users.admin.web;bundle-version="5.0.53"
When I deploy the module, it does not restart the fragment host bundle as it should (and did in Liferay 7.0). Restarting that bundle manually doesn't work either - the modified .jsp isn't used.
As a side note, we have other corejsphooks that work fine. This is the only one that doesn't work, so I must be missing something here.
Update: I am including the code as requested. Here are the four files in the module (not counting the default files like build.gradle and Language_en.properties that are created when the module is created) in the module.
bnd.bnd
Bundle-Version: 7.3.6.1
Fragment-Host: com.liferay.users.admin.web;bundle-version="5.0.53"
-sources: true
-jsp: *.jsp,*.jspf
user_action.jsp
<%--
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
--%>
<%# include file="/init.jsp" %>
<%# page import="com.liferay.petra.encryptor.Encryptor" %>
<%# page import="com.liferay.portal.kernel.util.HtmlUtil" %>
<%
UserSearch searchContainer = (UserSearch)request.getAttribute("liferay-ui:search:searchContainer");
String redirect = searchContainer.getIteratorURL().toString();
ResultRow row = (ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
User user2 = (User)row.getObject();
long userId = user2.getUserId();
String userLandingPage = null;
User currentUser = user2;
List<Organization> userOrganizations = currentUser.getOrganizations();
if (Validator.isNotNull(userOrganizations) && !userOrganizations.isEmpty())
{
// If user is member of more than one organization then it will take
// first organization from list
Organization organization = userOrganizations.get(0);
if (Validator.isNotNull(organization))
{
Group organizationGroup = organization.getGroup();
if (organizationGroup.getPrivateLayoutsPageCount() > 0)
{
String privateGroupURL = PropsUtil.get(PropsKeys.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING);
String groupFriendlyURL = organizationGroup.getFriendlyURL();
userLandingPage = privateGroupURL + groupFriendlyURL;
String encDoAsUserId = Encryptor.encrypt(
company.getKeyObj(), String.valueOf(userId));
userLandingPage = userLandingPage + "?doAsUserId=" + HtmlUtil.escapeURL(encDoAsUserId);
System.out.println("userLandingPage is: " + userLandingPage);
}
else
{
System.out.println(organizationGroup.getName() + " organization site doesn't have any private page. So default landing page will be used");
}
}
}
// System.out.println("Landing page is: " + userLandingPage);
%>
<liferay-ui:icon-menu
direction="left-side"
icon="<%= StringPool.BLANK %>"
markupView="lexicon"
message="<%= StringPool.BLANK %>"
showWhenSingleIcon="<%= true %>"
>
<%
boolean hasUpdatePermission = UserPermissionUtil.contains(permissionChecker, userId, ActionKeys.UPDATE);
%>
<c:if test="<%= hasUpdatePermission %>">
<portlet:renderURL var="editUserURL">
<portlet:param name="mvcRenderCommandName" value="/users_admin/edit_user" />
<portlet:param name="redirect" value="<%= redirect %>" />
<portlet:param name="p_u_i_d" value="<%= String.valueOf(userId) %>" />
</portlet:renderURL>
<liferay-ui:icon
message="edit"
url="<%= editUserURL %>"
/>
</c:if>
<c:if test="<%= UserPermissionUtil.contains(permissionChecker, userId, ActionKeys.PERMISSIONS) %>">
<liferay-security:permissionsURL
modelResource="<%= User.class.getName() %>"
modelResourceDescription="<%= user2.getFullName() %>"
resourcePrimKey="<%= String.valueOf(userId) %>"
var="permissionsUserURL"
windowState="<%= LiferayWindowState.POP_UP.toString() %>"
/>
<liferay-ui:icon
message="permissions"
method="get"
url="<%= permissionsUserURL %>"
useDialog="<%= true %>"
/>
</c:if>
<c:if test="<%= (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED || PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) && hasUpdatePermission %>">
<%
PortletURL managePagesURL = PortletProviderUtil.getPortletURL(request, user2.getGroup(), Layout.class.getName(), PortletProvider.Action.EDIT);
managePagesURL.setParameter("redirect", redirect);
%>
<liferay-ui:icon
message="manage-pages"
url="<%= managePagesURL.toString() %>"
/>
</c:if>
<c:if test="<%= !PropsValues.PORTAL_JAAS_ENABLE && PropsValues.PORTAL_IMPERSONATION_ENABLE && (userId != user.getUserId()) && !themeDisplay.isImpersonated() && UserPermissionUtil.contains(permissionChecker, userId, ActionKeys.IMPERSONATE) %>">
<liferay-security:doAsURL
doAsUserId="<%= userId %>"
var="impersonateUserURL"
/>
<liferay-ui:icon
message="impersonate-user"
target="_blank"
url="<%= Validator.isNotNull(userLandingPage) ? userLandingPage : impersonateUserURL %>"
/>
</c:if>
<c:if test="<%= UserPermissionUtil.contains(permissionChecker, userId, ActionKeys.DELETE) %>">
<c:if test="<%= !user2.isActive() %>">
<portlet:actionURL name="/users_admin/edit_user" var="restoreUserURL">
<portlet:param name="<%= Constants.CMD %>" value="<%= Constants.RESTORE %>" />
<portlet:param name="redirect" value="<%= redirect %>" />
<portlet:param name="deleteUserIds" value="<%= String.valueOf(userId) %>" />
</portlet:actionURL>
<liferay-ui:icon
message="activate"
url="<%= restoreUserURL %>"
/>
</c:if>
<portlet:actionURL name="/users_admin/edit_user" var="deleteUserURL">
<portlet:param name="<%= Constants.CMD %>" value="<%= user2.isActive() ? Constants.DEACTIVATE : Constants.DELETE %>" />
<portlet:param name="redirect" value="<%= redirect %>" />
<portlet:param name="deleteUserIds" value="<%= String.valueOf(userId) %>" />
</portlet:actionURL>
<c:if test="<%= userId != user.getUserId() %>">
<c:choose>
<c:when test="<%= user2.isActive() %>">
<liferay-ui:icon-deactivate
url="<%= deleteUserURL %>"
/>
</c:when>
<c:when test="<%= !user2.isActive() && PropsValues.USERS_DELETE %>">
<liferay-ui:icon-delete
url="<%= deleteUserURL %>"
/>
</c:when>
</c:choose>
</c:if>
</c:if>
</liferay-ui:icon-menu>
corejsphook.UserActionCustomJspBag.java
/**
* Copyright 2000-present Liferay, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package corejsphook;
import com.liferay.portal.deploy.hot.CustomJspBag;
import com.liferay.portal.kernel.url.URLContainer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
/**
* #author Scott McIntosh, ICF
*/
#Component(
immediate = true,
property = {
"context.id=UserActionCustomJspBag",
"context.name=User Action Custom JSP Bag",
"service.ranking:Integer=111"
}
)
public class UserActionCustomJspBag implements CustomJspBag
{
#Override
public String getCustomJspDir() {
return "META-INF/resources/";
}
#Override
public List<String> getCustomJsps() {
System.out.println("In getCustomJsps(). _customJsps is null?");
System.out.println(_customJsps == null);
return _customJsps;
}
#Override
public URLContainer getURLContainer() {
System.out.println("In getURLContainer()");
return _urlContainer;
}
#Override
public boolean isCustomJspGlobal() {
System.out.println("In isCustomJspGlobal()");
return true;
}
#Activate
protected void activate(BundleContext bundleContext) {
System.out.println("In activate()");
bundle = bundleContext.getBundle();
_customJsps = new ArrayList<>();
Enumeration<URL> entries = bundle.findEntries(
getCustomJspDir(), "*.jsp", true);
while (entries.hasMoreElements()) {
URL url = entries.nextElement();
System.out.println("Processing jsp: " + url);
_customJsps.add(url.getPath());
}
}
private List<String> _customJsps;
private final URLContainer _urlContainer = new URLContainer() {
#Override
public Set<String> getResources(String path) {
System.out.println("In getResources()");
Set<String> paths = new HashSet<>();
for (String entry : _customJsps) {
if (entry.startsWith(path)) {
paths.add(entry);
}
}
return paths;
}
#Override
public URL getResource(String name) {
System.out.println("In getResource()");
return bundle.getEntry(name);
}
};
private Bundle bundle;
}
gov.nysdot.rideshare.NYRideshareEnUsResourceBundle.java
ackage gov.nysdot.rideshare;
import com.liferay.portal.kernel.language.UTF8Control;
import java.util.Enumeration;
import java.util.ResourceBundle;
import org.osgi.service.component.annotations.Component;
#Component(
property = { "language.id=en_US" },
service = ResourceBundle.class
)
public class NYRideshareEnUsResourceBundle extends ResourceBundle {
#Override
protected Object handleGetObject(String key) {
return _resourceBundle.getObject(key);
}
#Override
public Enumeration<String> getKeys() {
return _resourceBundle.getKeys();
}
private final ResourceBundle _resourceBundle = ResourceBundle.getBundle(
"content.Language_en_US", UTF8Control.INSTANCE);
}
Update:
I have started from scratch, but I'm getting the same result.
I created a new module using:
$ blade create -t fragment gov.nysdot.user-action-hook --host-bundle-symbolic-name com.liferay.users.admin.web --host-bundle-version 5.0.53
I then copied user_action.jsp from source (/modules/apps/users-admin/users-admin-web/src/main/resources/META-INF/resources/user_action.jsp).
To test, I simply duplicated the separator line at line 156 () so that I'd have a visual clue. If the override worked I'd see two separator lines.
I built with 'grade build' and deployed to my server. It did not restart the com.liferay.users.admin.web bundle, and no changed were present.
Now, there are practically no changes from what the module creation script created.
What strikes me in your code/description:
The jsp is a module's jsp, not a core jsp. Thus I wouldn't expect a CustomJspBag, but rather follow the module_jsp_override sample
A fragment bundle will never be ACTIVE, only RESOLVED (as in OSGi bundle lifecycles). Thus, it can deliver files that override a host bundle's files, but none of its own code. You're providing separate services, that certainly wouldn't be available and started - they should live in other bundles. Consider a fragment bundle as passive.
Thus, without turning your files into a project to try, I'd assume that this is the problem at hand.
Convert the bundle to a module-jsp-override project (no java code, pay attention to bnd.bnd). Make sure that the JSP is still what it needs to be: You can't just copy the 7.0 JSP to 7.3 and assume that those changes still accurately implement what you need. Rather, you'll need a 3-way-merge between the stock 7.0 version, your modifications, and the stock 7.3 jsp.
I need to make a portlet which would show all registred users in liferay.
Im not asking you to write all code here, but I would aprreciate if u could present an step-by-step plan of actions, cause I really don't understand how to get info from database.
UPD:
1. I can`t solve what should I import in java file.
import java.io.IOException;
import java.util.List;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.transaction.SystemException;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class ShowUsers extends MVCPortlet {
public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException{
Log log = LogFactoryUtil.getLog(ShowUsers.class);
List<User> users = null;
try {
users = UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
} catch (com.liferay.portal.kernel.exception.SystemException e) {
log.info("Exception happened");
}
renderRequest.setAttribute("allUsers", users );
super.render(renderRequest, renderResponse);
}
}
===================
My jsp file:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# page import="java.util.List" %>
<%# page import="com.liferay.portal.model.User" %>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<%
List<User> thatusers = renderRequest.getAttribute("allUsers");
%>
<ul>
<% for (User user : thatusers) { %>
<li><%= user %></li>
<% } %>
</ul>
And after this code I have strange info about all users and I need only it's name! this:
{uuid=fb7224c0-2488-45c1-97b8-5608450435a6, userId=20199, companyId=20155, createDate=2016-06-06 08:14:14.0, modifiedDate=2016-06-06 08:14:14.0, defaultUser=false, contactId=20200,
To get all users take a look at UserLocalServiceUtil.getUsers()
In your portlet class you need to pass this list to the jsp you are serving:
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
List<User> users = UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
renderRequest.setAttribute("allUsers", users );
super.doView(renderRequest, renderResponse);
}
And than in your jsp iterate the allUsers list using JSTL to get a user object.
getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS); would retrieve all the users, instead of QueryUtil.ALL_POS you can specifie start and end if you need to paginate the result.
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ValidatorException;
import com.liferay.util.bridges.mvc.MVCPortlet;
public class GreetingMessage extends MVCPortlet {
public static final String GREETING = "greeting";
public static final String DEFAULT_GREETING = "Hello! It's my default greeting message";
#Override
public void render(RenderRequest request, RenderResponse response)
throws IOException, PortletException {
PortletPreferences preferences = request.getPreferences();
request.setAttribute(GREETING,
preferences.getValue(GREETING, DEFAULT_GREETING));
super.render(request, response);
}
public void updateGreeting(ActionRequest request, ActionResponse response)
throws ValidatorException, IOException, ReadOnlyException {
String greeting = request.getParameter("greeting");
PortletPreferences prefs = request.getPreferences();
if (greeting != null) {
prefs.setValue(GREETING, greeting);
prefs.store();
request.setAttribute(GREETING, greeting);
}
}
}
view.jsp:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<p>${greeting}</p>
<portlet:renderURL var="editGreetingURL">
<portlet:param name="mvcPath" value="/html/greetingmessage/edit.jsp"/>
</portlet:renderURL>
<p>Edit greeting</p>
edit.jsp
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
<%# page import="javax.portlet.PortletPreferences" %>
<portlet:defineObjects />
<portlet:actionURL name="updateGreeting" var="updateGreetingURL">
</portlet:actionURL>
<aui:form action="<%= updateGreetingURL %>" method="post">
<aui:input label="greeting" name="greeting" type="text" value="${greeting}" />
<aui:button type="submit" />
</aui:form>
<portlet:renderURL var="viewGreetingURL">
<portlet:param name="mvcPath" value="/html/greetingmessage/view.jsp" />
</portlet:renderURL>
<p>← AND NOW IT'S BACK</p>
It's tested code of my "edit-greeting" portlet. The question is, how can I make localization??? I've read a lot of docs but it's all for nothing. I created in WEB-INF folder src/language.properties and src/language_es.properties. What should I do next? Help me please. #Shivam
To Answer your question
1)You can handle your attributes and portlet preferences in render method and set them as attributes in render request,which can be subsequently read in your jsp via some scripting language like jstl
2)There is no need to make changes in portlet.xml file.
The init params as the name suggests are added to provide some params needed for initializing a portlet view.
You need to make the below changes to the render method
public void render(RenderRequest req,RenderResponse res) throws IOException, PortletException
{
String greeting = req.getParameter("greeting");
PortletPreferences prefs = req.getPreferences();
String defaultGreeting="Hello! Welcome to our portalOLOLOLOLOL.";
if(prefs.getValue("greeting","true")==null)
{
prefs.setValue("greeting", defaultGreeting);
}
if (greeting != null)
{
prefs.setValue("greeting", greeting);
prefs.store();
req.setAttribute("greeting", prefs.getValue("greeting","true"));
}
else
{
req.setAttribute("greeting", prefs.getValue("greeting","true"));
}
super.render(req,res);
}
There will not be any changes required in view.jsp and edit.jsp(apart from removing code),Hence I forgot to mention the same.
As for the render method,the best approach would be defintely to use action url and use action method,but since it seems you are looking to try out some approach and to make mininmum changes to your,I have kept it render only.
As for the code,the prefs.getValue("greeting","true") checks whether a certain attribute is present in portlet preferences or not.
Updated with process action
public class NewPortlet extends MVCPortlet {
public static final String GREETING="greeting";
#Override
public void render(RenderRequest req,RenderResponse res) throws IOException, PortletException
{
PortletPreferences prefs = req.getPreferences();
String defaultGreeting="Hello! Welcome to our portalOLOLOLOLOL.";
if(prefs.getValue(GREETING,"true")==null)
{
prefs.setValue(GREETING, defaultGreeting);
prefs.store();
}
req.setAttribute(GREETING, prefs.getValue(GREETING,"true"));
super.render(req,res);
}
public void updateGreeting(ActionRequest req,ActionResponse res) throws ValidatorException, IOException, ReadOnlyException
{
String greeting = req.getParameter("greeting");
PortletPreferences prefs = req.getPreferences();
if (greeting != null)
{
prefs.setValue(GREETING, greeting);
prefs.store();
req.setAttribute(GREETING, greeting);
}
}
}
Updates in edit jsp
<portlet:actionURL name="updateGreeting" var="updateGreetingURL">
</portlet:actionURL>
<aui:form action="<%= updateGreetingURL %>" method="post">
<aui:input label="greeting" name="greeting" type="text" value="${greeting}" />
<aui:button type="submit" />
</aui:form>
I want to display users list on liferay. and I am having problem with it.
Here is my action class.
public void userList(ActionRequest actionRequest, ActionResponse actionResponse) throws SystemException {
// Todo Logic for user code
try {
int countUser = UserLocalServiceUtil.getUsersCount();
log.info("User Present In DB" + countUser);
List < User > users = UserLocalServiceUtil.getUsers(0, countUser);
PortletSession sessions = actionRequest.getPortletSession();
sessions.setAttribute("users", users);
log.info("Session set from My Portlet" + sessions.getAttribute("users"));
for (User user: users) {
if (user != null) {
log.info("UserID--:" + user.getUserId() + "UserCompanyID-:" + user.getCompanyId() + "UserEmail-:" + user.getEmailAddress() +
"UserScreenName--:" + user.getScreenName());
}
}
and how I am trying to get the users list on jsp.
<%#page import="com.test.UserList.userList"%>
<%#page import="java.util.ArrayList"%>
<%#page import="com.liferay.portal.model.User"%>
<%#page import="java.util.List"%>
<%#page import="javax.portlet.PortletSession"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%#taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
<portlet:defineObjects />
<%
PortletSession session2 = renderRequest.getPortletSession();
ArrayList<User> users = (ArrayList) session2.getAttribute("users");
if(users!=null){
%>
<b>Name: </b><%=users.get(users) %>
<%} %>
and i am getting the value is null
i want to display all the users name in list
Another option to get list of all users is
UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS);
and then iterate it to fetch each user.
There is no issue with your logic in putting user-list in session, the list is getting populated and set in session accurately.
However, on JSP, there are couple of issues:
renderRequest is undefined.
Cast exception (UnmodifiableList cannot be cast to java.util.ArrayList) for user-list.
You are not iterating list and getting user objects properly.
So, you need to do as following on your JSP:
<%#page import="java.util.ArrayList"%>
<%#page import="javax.portlet.RenderRequest"%>
<%#page import="com.liferay.portal.model.User"%>
<%#page import="javax.portlet.PortletSession"%>
<%
RenderRequest renderRequest =
(RenderRequest) request.getAttribute("javax.portlet.request");
PortletSession session = renderRequest.getPortletSession();
List<User> users = (List<User>) session.getAttribute("users");
if(users != null){
for(User user : users){
%>
<b>Name: </b><%=user.getLastName() + ", " + user.getFirstName() %><br />
<%}
}%>
(Tested Code)
I have a custom webpart within Sharepoint and am trying to apply some ajax to the webpart.
The same code works within a .net web application but not within a sharepoint web part.
The code from the .net web application is shown below (the aspx page and the code behind) which works fine.:
ASPX File
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
var loc = window.location.href;
$.ajax({
type: "POST",
url: loc + "/GetMessage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id="Result">Click here for the time.</div>
<asp:Button ID="btnClick" runat="server" Text="Button" />
</asp:Content>
.CS File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication3
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetMessage()
{
return "Codebehind method call...";
}
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
}
The text "Click here for the time" changes to "Code behind method call" when I click on it without doing a postback. I can step into the code and this calls the method GetMessage() in the code behind within a .net web application.
However this does not work on a webpart within sharepoint 2010. Does anyone have any ideas?
Another option is to create a SharePoint Application Page. Here is your code slightly modified to work as an Application Page (uses SharePoint Master Page content sections, and the AJAX points to the application page:
<%# Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%# Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ApplicationPageWS.aspx.cs" Inherits="WebMethod.Layouts.WebMethod.ApplicationPageWS" DynamicMasterPageFile="~masterurl/default.master" %>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Localizable="false" Name="js/jquery-1.8.2.js"></SharePoint:ScriptLink>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "**/_layouts/WebMethod/ApplicationPageWS.aspx/GetMessage**",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
},
error: function (msg) {
alert(msg.responseText);
}
});
});
});
</script>
<div id="Result">Click here for the time.</div>
<asp:Button ID="btnClick" runat="server" Text="Button" />
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Application Page
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
My Application Page
</asp:Content>
Next change your service-side to inherit from LayoutsPageBase instead of WebPart:
using System;
using System.Web.UI;
using System.Web.Services;
using Microsoft.SharePoint.WebControls;
namespace WebMethod.Layouts.WebMethod
{
public partial class ApplicationPageWS : LayoutsPageBase
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetMessage()
{
return "Codebehind method call...";
}
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
}
Hope this solution work in your situation, if not, and you need to call a web service from a web part, you will need to create the web service outside of your Web Part. This is nicely explained at http://dbremes.wordpress.com/2011/01/03/ajax-style-web-parts-in-sharepoint-the-easy-way/
Steve
First make sure that all needed js files are deployed and loaded correctly. Lookup the urls in the html source and copy them in a new tab and see if they load correctly.
Also try to put all JavaScript files on the server ( so no 'https://ajax.googleapis.com/...' urls). I once had problems with crossdomain scripting permissions.
There might also be a conflict with different JavaScript libraries being loaded. For jQuery within a SharePoint context I usually use the 'noConflict' option.
var $j = jQuery.noConflict();
$j(document).ready(function() {
.....
I just want to say you have to use POST you cannot use a GET found that out the hard way.