Sharepoint 2010 JQuery Ajax not working - sharepoint

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.

Related

Razor Component event not firing in Razor Page

How do I get events to fire in a Razor component running in a Razor page?
My Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapBlazorHub();
});
}
My Razor Page calling the component:
#page
#model DocketDetail.OrderModel
#{
Layout = null;
}
#using RelationalObjectLayerCore;
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/lib/jquery/dist/jquery.js"></script>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="_framework/blazor.server.js"></script>
<script src="~/js/site.js"></script>
<title>Order</title>
</head>
<body>
<component type="typeof(Component.Filedby)" render-mode="ServerPrerendered" />
</body>
Everything displays properly.
My component:
#using Microsoft.AspNetCore.Components
#code {
private void SearchPerson()
{
string x = "TEST";
}
}
<button #onclick="SearchPerson">Search</button>
Obviously this is pared down from my actual code... but I can not figure out how to get "SearchPerson" to fire in the Razor Component.
Found this:
https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.1#integrate-razor-components-into-razor-pages-and-mvc-apps
With this little note:
Add a <script> tag for the blazor.server.js script inside of the
closing </body> tag:
HTML
<script src="_framework/blazor.server.js"></script>
Moved my script tag and it now works.
Thanks everyone for your suggestions.
I think I see what you're trying to do. Not sure if that is going to work they way you intend. The component will get rendered using Blazor, but the code attached to the button won't function. Put the #code{} for your button on the page that gets loaded. Or you can do an OnInitialized() overload if you want that code to run each time the page is loaded.
Also, make sure that the Blazor is rendering properly in the browser. Use F12 and make sure it says connected.
https://learn.microsoft.com/en-us/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1

Allow page layout to hide control on master page

If I want to use my regular master page for a new page layout, except I don't want the main navigation menu control (a 3rd party control) to be visible, how can I let the page layout hide it? In asp.net I would expose a public property or method on the master page and then call it from the child page, but not sure what can be done in SharePoint since there is no code behind or discernible master page class.
I got it working like this but I'm not in love with the implementation.
On Master Page:
...
<c:Menu id="myMenu" runat="server" />
...
</form>
</body>
</html>
<script runat="server">
public bool IsConsumerNavVisible
{
set
{
myMenu.Visible = value;
}
}
</script>
On PageLayout:
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
System.Reflection.PropertyInfo pi = Page.Master.GetType().GetProperty("IsConsumerNavVisible");
pi.SetValue(Page.Master, false, null);
}
</script>
So I exposed a public property on the master page to set the visibility and then used reflection on the PageLayout to find & set that property. I tried putting the PageLayout code in just a <% %> script block and it executed but the menu would end up visible anyway. Putting it in a Page_Load event handler fixed that. If there is a better way I'm all ears.

new to Liferay , i am unable to navigate through Pages using renderURL

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.

Datetime picker for share point project

Does anyone have any example on how to put a date time picker inside a sharepoint project?
more specifically to put a date time picker in the gridview..
I've been googling for hours and still couldn't find example that works..
most of the example is for normal web project and not for sharepoint project..
and btw I've tried putting the datetimecontrol inside the gridview, but it doesn't work as well.
Thanks in advance.
I love to use jQuery UI's Datepicker:
http://jqueryui.com/demos/datepicker/
To implement in a GridView, I normally make an editable text box and just apply the class to it, which would invoke the datepicker:
<asp:GridView ID="gvClientDetails" runat="server">
<Columns>
<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
<asp:TextBox runat="server" ID="myTextBox" CssClass="dateTextBox" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="myLabel" runat="server" Text='<%# Eval("myDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and then make use of the below javascript (registered on your page or site wide):
$('.dateTextBox').each(function () {
$(this).datepicker(
{
changeMonth: true,
changeYear: true,
dateFormat: 'yy/mm/dd'
});
})
As for applying something like this to your sharepoint site, this should assist you:
http://blogs.lessthandot.com/index.php/WebDev/UIDevelopment/Javascript/adding-a-jquery-date-picker-to-sharepoint
Just use common standard SP DateTimeControl.
This is how we do it :
/// <summary>
/// Get common SP DateTimeControl with current DateOnly settings and MethodToProcessDateChanged
/// </summary>
public static DateTimeControl Cd(this bool DateOnly, bool AutoPostBack = false,
DateTime? SelectedDate = null, Func<bool> MethodToProcessDateChanged = null)
{
var d = new DateTimeControl();
d.DateOnly = DateOnly;
d.AutoPostBack = AutoPostBack;
if (SelectedDate != null)
d.SelectedDate = SelectedDate.Value;
if (MethodToProcessDateChanged != null)
d.DateChanged += (o, e) => { MethodToProcessDateChanged();};
return d;
}
See more details with some common usage samples here

Getting last item from the SharePoint list using CAML queries

I want to get the last item from a SharePoint list, but since I am new to SharePoint, I am having a really hard time accomplishing anything. First of all, this CAML API is tough to find, then I really don't have any programming experience either.
Anyway, here's my logic in a ASPX page. I want to display the last item:
<html>
<head>
<meta name="WebPartPageExpansion" content="full" />
<meta name="ProgId" content="SharePoint.WebPartPage.Document" />
<script runat="server" type="">
protected void sevak(object sender, EventArgs e)
string lastitem;
try {
using (SPSite objsite = new SPSite()) {
using (SPWeb objWeb = objSite.OpenWeb(....)) {
SPList objList = objWeb.Lists["List"];
SPQuery objQuery = new SPQuery();
objQuery.Query = "<OrderBy><FieldRef Name='Number' Ascending='False'/></OrderBy><RowLimit>1</RowLimit>";
objQuery.Folder = objList.RootFolder;
SPListItemCollection colItems = objList.GetItems(objQuery);
if (colItems.Count>0) {
lastitem=colItems[0];
}
}
}
}
catch (Exception ex) { }
return lastitem;
</script>
<SharePoint:CssLink runat="server"></SharePoint:CssLink>
<SharePoint:ScriptLink runat="server" language="javascript" name="core.js"></SharePoint:ScriptLink>
</head>
<body>
<form id="form1" runat="server">
<h1>T-Site</h1>
<p>
<asp:Button runat="server" Text="Submit" id="Button1" OnClick="sevak" OnClientClick="javascript:window:alert('Your Request for a document number has been received');"></asp:Button>
</p>
</body>
</form>
</html>
for CAML query use U2U CAML query builder tool its very easy to use
second you have to execute your object model code on a server on which SharePoint is installed logic is correct but i see some where problem with your syntax
for syntax take help from this post
http://www.a2zdotnet.com/View.aspx?Id=114

Resources