Thursday, 11 July 2013

Umbraco and MVC tips

 
How to access Umbraco Current Node 
 
public class CommentSurfaceController : SurfaceController
{
    private readonly IUmbracoApplicationContext context;
    public CommentSurfaceController(IUmbracoApplicationContext context)
    {
        this.context = context;
    }
}
 

Implementation surface controller

I have search for which I want to implement autocomplete. 

My json result will be based on AutoCompleteSearchResult:
 
 public class AutoCompleteSearchResult
    {
        public string value { get; set; }
        public string data { get; set; }
    }
 
My controller

  public class SearchController: SurfaceController
    {
        public JsonResult Index(RenderModel model)
        {

            var result = new List<AutoCompleteSearchResult>();

            result.Add(new AutoCompleteSearchResult(){data = "1", value = "test1"});
            result.Add(new AutoCompleteSearchResult(){data = "2", value = "test2"});
            result.Add(new AutoCompleteSearchResult(){data = "3", value = "test3"});


            return new JsonResult(){Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
        }
    }

 
If you are using surface controllers your link has to have prefix:
 
umbraco/surface/ 

 
Access the action on url
 
http://yourserver/umbraco/surface/Search/index/ 
 

Binding tip

If you are binding RenderMvcController to controller make sure that 
DataType and Controller name are the same
 
SearchPage , SearchPageController

Load data using uQuery

umbraco.NodeFactory.Node node = uQuery.GetNodesByName("Page Name")
    .Where(n => n.NodeTypeAlias == "NodeTypeAlias").FirstOrDefault();

if (node != null)
{
    //...
}
GetNodesByType(string or int):
umbraco.NodeFactory.Node node = uQuery.GetNodesByType("NodeTypeAlias")
    .Where(n => n.Name == "Page Name").FirstOrDefault();

if (node != null)
{
    //...
}