4

Update: this is what my url is trying to resolve to:

/home/about us/api/sitecore/findanaffiliate/getaffiliate/

so here is my Ajax :

<script type="text/javascript">
    $("#AffiliateList").change(function () {
        var textval = $("AffiliateList :selected").text();
        var selected = $("#AffiliateList :selected").val();

        $.ajax({
            type: "GET",
            url: "api/Sitecore/FindAnAffiliate/GetAffiliate/",
            data: {id: selected},
            content: "html",
            success: function (response) {

                $("#affiliateDetail").empty();
                $("#affiliateDetail").append(response);
            },
            error: function (jqHRX, textStatus, errorThrown) {
                alert(jqHRX);
                alert(errorThrown);
                alert(textStatus);
            }



            })
    })
</script>

when I run the this in Sitecore preview mode everything executes fine, when I type the url into my browser and bring up the page... the java script is being executed, but the url is getting a 400 level error. I am running in the same environment.

here is the controller: findAnAffiliate is NOT being hit unless I am in Preview mode:

namespace Website.Controllers
{
    public class FindAnAffiliateController : Controller
    {
        // GET: findAnAffiliate
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FindAnAffiliate()
        {
            var dataSourceId = RenderingContext.CurrentOrNull.Rendering.DataSource;
            var dataSourceItem = Sitecore.Context.Database.GetItem(dataSourceId);

            var model = new AffiliateViewModel();
            model.title = dataSourceItem.Fields["Title"].Value;
            model.description = dataSourceItem.Fields["Description"].Value;
            model.affiliateList = model.affiliates();

            var selectedItem = model.affiliateList.FirstOrDefault();
            var affiliateItem = Sitecore.Context.Database.GetItem(selectedItem.Value);

            var affiliateDetail = new Affiliate();

            Sitecore.Data.Fields.MultilistField SponsorLinks = affiliateItem.Fields["Sponsors"];
            var sponsorLinkItems = SponsorLinks.GetItems();

            var count = 0;
            foreach (Sitecore.Data.Items.Item item in sponsorLinkItems)
            {


                var ImageLogo = (Sitecore.Data.Fields.ImageField)item.Fields["Image"];
                var ImageLogoUrl = "";
                if (ImageLogo.Value != "" && ImageLogo != null)
                {
                    ImageLogoUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(ImageLogo.MediaItem);
                }
                var linkName = item.Fields["Link Text"].Value;
                var ImageUrl = (Sitecore.Data.Fields.LinkField)item.Fields["Link"];
                var friendlyLinkUrl = ImageUrl.GetFriendlyUrl();

                if (count == 0)
                {
                    affiliateDetail.sponsor1_ImageUrl = ImageLogoUrl;
                    affiliateDetail.sponsor1_linkText = linkName;
                    affiliateDetail.sponsor1_linkUrl = friendlyLinkUrl;
                }

                if (count == 1)
                {
                    affiliateDetail.sponsor2_ImageUrl = ImageLogoUrl;
                    affiliateDetail.sponsor2_linkText = linkName;
                    affiliateDetail.sponsor2_linkUrl = friendlyLinkUrl;
                }

                count++;
            }

            affiliateDetail.title = affiliateItem.Fields["Affiliate Name"].Value;
            var linkUrl =(Sitecore.Data.Fields.LinkField) affiliateItem.Fields["Affiliate Link"];
            affiliateDetail.linkText = linkUrl.Text != "" ? linkUrl.Text : "No Link Available";
            affiliateDetail.linkUrl = linkUrl.GetFriendlyUrl();
            affiliateDetail.description = affiliateItem.Fields["Description"].Value;
            model.affiliate = affiliateDetail;


            return View(model);
        }

        public ActionResult GetAffiliate(string id)
        {
            var model = new Affiliate();

            var affiliateItem = Sitecore.Context.Database.GetItem(id);

            Sitecore.Data.Fields.MultilistField SponsorLinks = affiliateItem.Fields["Sponsors"];
            var sponsorLinkItems = SponsorLinks.GetItems();

            var count = 0;
                foreach (Sitecore.Data.Items.Item item in sponsorLinkItems)
                {


                    var ImageLogo = (Sitecore.Data.Fields.ImageField)item.Fields["Image"];
                    var ImageLogoUrl = "";
                    if (ImageLogo.Value != "" && ImageLogo != null)
                    {
                        ImageLogoUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(ImageLogo.MediaItem);
                    }
                    var linkName = item.Fields["Link Text"].Value;
                    var ImageUrl = (Sitecore.Data.Fields.LinkField)item.Fields["Link"];
                    var friendlyLinkUrl = ImageUrl.GetFriendlyUrl();

                if (count == 0)
                {
                    model.sponsor1_ImageUrl = ImageLogoUrl;
                    model.sponsor1_linkText = linkName;
                    model.sponsor1_linkUrl = friendlyLinkUrl;
                }

                if (count == 1)
                {
                    model.sponsor2_ImageUrl = ImageLogoUrl;
                    model.sponsor2_linkText = linkName;
                    model.sponsor2_linkUrl = friendlyLinkUrl;
                }

                count++;
                }


            model.title = affiliateItem.Fields["Affiliate Name"].Value;
            var linkUrl = (Sitecore.Data.Fields.LinkField)affiliateItem.Fields["Affiliate Link"];
            model.linkText = linkUrl.Text != "" ? linkUrl.Text : "No Link Available";
            model.linkUrl = linkUrl.GetFriendlyUrl();
            model.description = affiliateItem.Fields["Description"].Value;
            return PartialView(model);
        }
    }
}

Lastly, here is the View

@model Website.ViewModels.AffiliateViewModel

<div class="container">

    <div class="headline-container">
        <div class="headline-lines"></div>
        <h2 class="text-center">@Model.title</h2>
        <div class="headline-lines"></div>
    </div>

    <div class="row">
        <div class="col-sm-6">
            <p>@Model.description</p>
        </div>

        <div class="col-sm-6">
            @Html.DropDownList("AffiliateList", Model.affiliateList as SelectList, "", new { @id = "AffiliateList", @class = "form-control input-lg" })
        <div id="affiliateDetail">
            <h4>@Model.affiliate.title</h4>
            <p class="affiliateLink"><a href="@Model.affiliate.linkUrl">@Model.affiliate.linkText</a></p>
            <p>@Model.affiliate.description</p>

            <div class="col-xs-6">
                <img class="img-responsive" src="@Model.affiliate.sponsor1_ImageUrl">
                <p class="affiliateLink small_p"><a href="@Model.affiliate.sponsor1_linkUrl">@Model.affiliate.sponsor1_linkText</a></p>
            </div>

            <div class="col-xs-6">
                <img class="img-responsive" src="@Model.affiliate.sponsor2_ImageUrl">
                <p class="affiliateLink small_p"><a href="@Model.affiliate.sponsor2_linkUrl">@Model.affiliate.sponsor2_linkText</a></p>
            </div> 

        </div>

    </div><!--row-->



</div><!--container-->
      </div><!-- /content container-->    
<script type="text/javascript">
    $("#AffiliateList").change(function () {
        var textval = $("AffiliateList :selected").text();
        var selected = $("#AffiliateList :selected").val();

        $.ajax({
            type: "GET",
            url: "api/Sitecore/FindAnAffiliate/GetAffiliate/",
            data: {id: selected},
            content: "html",
            success: function (response) {

                $("#affiliateDetail").empty();
                $("#affiliateDetail").append(response);
            },
            error: function (jqHRX, textStatus, errorThrown) {
                alert(jqHRX);
                alert(errorThrown);
                alert(textStatus);
            }



            })
    })
</script>
3

I would recommend creating a custom route for Ajax functionality that doesn't reside in the Sitecore Shell. From my understanding, using the default route of /api/Sitecore only works if you are logged in, which is why it works in preview but not the rest of the time on your site. Now I'm sure there is a way to change this permission, but you wouldn't want to, since it could open up new security concerns.

To define a custom route you should create a class that defines the route:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "Default",
        url: "FindAnAffiliate/GetAffiliate",
        defaults: new { controller = "FindAnAffiliate", action = "GetAffiliate" }
    );
}

And then you would define a patch config, something like this:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initialize>
        <processor type="mvc.Pipelines.LoadRoutes,mvc" patch:after="processor[@type='Sitecore.Pipelines.Loader.EnsureAnonymousUsers, Sitecore.Kernel']" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

The type should match the namespace and assembly for where you placed your RegisterRoutes definition.

This is a helpful resource on the topic:

https://doc.sitecore.net/sitecore_experience_platform/developing/developing_with_sitecore/mvc/use_mvc_routing

I have added the following to the RouteConfig.cs

routes.MapRoute(
        name: "Default",
        url: "FindAnAffiliate/GetAffiliate",
        defaults: new { controller = "FindAnAffiliate", action = "GetAffiliate" }
    );

Then I created this LoadRoutes.cs

 using System.Web.Routing;
namespace Website.Pipelines
{
    using Sitecore.Diagnostics;
    using Sitecore.Pipelines;

    // TODO: \App_Config\include\LoadRoutes.config created automatically when creating LoadRoutes class.

    public class LoadRoutes
    {
        public void Process(PipelineArgs args)
        {
            Log.Info("Sitecore is starting", this);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

And this was created under App.Config\Include

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initialize>
        <processor type="mvc.Pipelines.LoadRoutes,mvc" patch:after="processor[@type='Sitecore.Pipelines.Loader.EnsureAnonymousUsers, Sitecore.Kernel']" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

it is still trying to resolve to /home/AboutUs/api/Sitecore/FindAnAffiliate/GetAffiliate ... which is giving me a 404 error

| improve this answer | |
  • Greetings Dylan, thank you so much!! I will review this. Does it matter where I define the RegisterRoutes? and as far the patch, do I add this config file under the same name space, or is there a specific place to place this? – Paul T. Rykiel Sep 17 '17 at 19:41
  • Hi Dylan ... check out my response below – Paul T. Rykiel Sep 22 '17 at 14:14
  • @PaulT.Rykiel Looks good! – Dylan Young Sep 22 '17 at 17:28
0

the way I got this to work ... I did not have to change Route.config.cs, I did create a folder called Pipelines/ and in it I added a "LoadProcessor" which is part of Sitecore. the Load Processor is below:

using System.Web.Mvc;
using System.Web.Routing;

namespace Website.Pipelines
{
    using Sitecore.Diagnostics;
    using Sitecore.Pipelines;

    // TODO: \App_Config\include\LoadRoutes.config created automatically when creating LoadRoutes class.

    public class LoadRoutes
    {
        public void Process(PipelineArgs args)
        {
            Log.Info("Sitecore is starting", this);
            RouteTable.Routes.MapRoute("Find an Affiliate api", "api/findanaffiliate/{action}", new { controller = "FindAnAffiliate" });
            RouteTable.Routes.MapRoute("Category Search", "api/multiselectandsearch/{action}", new { controller = "MultiSelectAndSearch" });
            RouteTable.Routes.MapRoute("Magazine Archive", "api/wildlifemagazinearchive/{action}", new { controller = "WildlifeMagazineArchive" });
        }
    }
}

This next xml is created for you, under App_config/Include: this will be added to the Initialization Pipeline

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initialize>
        <processor type="Website.Pipelines.LoadRoutes,Website" patch:after="processor[@type='Sitecore.Pipelines.Loader.EnsureAnonymousUsers, Sitecore.Kernel']" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

Then I changed my ajax url :

<script type="text/javascript">
    $("#AffiliateList").change(function () {
        var textval = $("AffiliateList :selected").text();
        var selected = $("#AffiliateList :selected").val();
        $.ajax({
            type: "GET",
            url: "/api/FindAnAffiliate/GetAffiliate/",
            data: { id: selected },
            content: "html",
            success: function (response) {

                $("#affiliateDetail").empty();
                $("#affiliateDetail").append(response);
            },
            error: function (jqHRX, textStatus, errorThrown) {


            }



        })

    })
</script>

So, notice the url matches the routing in the Load Processor.

| improve this answer | |
0

Just add a slash in front of the URL.

url: api/Sitecore/FindAnAffiliate/GetAffiliate/,

url: /api/Sitecore/FindAnAffiliate/GetAffiliate/,

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.