1
votes

I'm using Sitecore 7.1 and an MVC 4 project.

I'm trying to make a search box which will search news into a bucket and return the result as JSON.

So i read that blog post : http://keeplearningandsharing.wordpress.com/2013/12/13/sitecore-mvc-with-ajax/

and try to do the same but it does not work.

What i did :

1) I created a controller named NewsOverviewController where i put two methods

ActionResult Start() (HttpGet) which return my view with the searchbox
JsonResult Starts(InpurtParams) which perform the search

2) In sitecore, i created my Controller Rendering and add the action start to it.

3) i register a new route in RouteConfig.cs (i put it before the sitecore route and after, didn't change anythings)

  routes.MapRoute(
          name: "search",
          url: "api/NewsOverview/{action}/{id}",
          defaults: new { controller = "NewsOverview", action = "Starts", id = UrlParameter.Optional }
        );

4) I put the following code in my view :

<script>
function getSearchResult() {
    var inputparams = {};
    inputparams.SearchTerm = document.getElementById("searchTerm").value;

    try {
        $.getJSON("/api/NewsOverview/starts", inputparams, displaySearchResult);
    }
    catch (ex) {
        alert("Error : " + ex.message);
    }
}

function displaySearchResult(data) {
    $.each(data, function (i, result) {
        $("#searchresult").append(result.Name + " - " + result.Url + "<br/>");
    });

};
</script>

<div>
    <input type="text" name="searchTerm" id="searchTerm" value="test"/>
    <input type="button" onclick="getSearchResult();"/>
    <div id="searchresult"></div>
</div>

My problem when i try to use the search : He didn't find the url (404 (Page not found) ) : {host}/api/NewsOverview/start?SearchTerm=test

I'm pretty new to MVC, so i miss maybe somethings ...

2

2 Answers

0
votes

Ok ...

I found the problem by reading two more time the post from John West ;)

http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2012/06/Use-JSON-and-MVC-to-Retrieve-Item-Data-with-the-Sitecore-ASPNET-CMS.aspx

The RegisterRoutes.cs in App_Start does not register the routes, but you have to register your routes via the Pipelines.

0
votes

We register routes in the Application_Start event and not in any pipelines. It is working well for us.

  protected void Application_Start()
  {
     RegisterRoutes(RouteTable.Routes);
  }

  private void RegisterRoutes(RouteCollection routes)
  {
    routes.MapRoute("NameOfRoute", "Path To Use from Ajax", new { controller = "Controller Class,Assembly", action = "Name Of Method On Controller" });
  }