how to fetch componentPresentation from brokerdb? - tridion

I am new to SDL Tridion,just exploring content delivery.
I used below code in the TBB of my pagetemplate
<% ComponentPresentationFactory factory = new ComponentPresentationFactory("tcm:0-6- 1");
ComponentPresentation ps = factory.GetComponentPresentationFactory("tcm:6-9841","tcm:6-9858-32");
if(ps!=null )
{
string output="";
output=ps.Content;
Literal1.Text=output;
}
%>
<asp:Literal id="Literal1"Text="" runat="server"<</asp:Literal>
I have published that component and used a dynamic component template.
But no content is reflecting on the page.Did i missed something?

Try removing the whitespace from the uri tcm:0-6-1 and your code should read factory.GetComponentPresentation("tcm:6-9841","tcm:6-9858-32");

Related

How to retrieve a sitecore hyperlink?

Situation:
Imagine that I have an item(page) located at 'sitecore/Content/Home/mypage' in my content tree. I want to create a hyperlink to this item in my .aspx layout.
Question:
How can I create a hyperlink to this item in my .aspx layout?
(Can't remember the proper syntax for <asp:Hyperlink>)
If you need to get an Item's url in code, whether or not you're using it in a link, you can use Sitecore.Links.LinkManager.GetItemUrl(item, options).
I recommend against using it with a single parameter (GetItemUrl(item)), as it wont respect configuration options (such as disabling the language string as part of the path: /en/path/to/item might appear instead of /path/to/item).
To use the config options, you can clone the default URL options:
var opts = (UrlOptions) UrlOptions.DefaultOptions.Clone();
var url = LinkManager.GetItemUrl(item, opts);
I use this often enough that I use the following extension method:
public static string GetUrl(this Item source, bool absolutePath = false)
{
if (source == null)
throw new ArgumentNullException("source");
var options = (UrlOptions) UrlOptions.DefaultOptions.Clone();
options.AlwaysIncludeServerUrl = absolutePath;
return LinkManager.GetItemUrl(source, options);
}
The advantage to using this format is that it allows you to identify an item by ID and link to it no matter where it lies in the content tree.
I'm not sure if in Adil's example, the URL is processed by the LinkProvider?
I would usually bind the NavigateUrl property in my code-behind
<asp:HyperLink ID="hlHyperLink" runat="server" Text="my link text" />
then in C#
hlHyperLink.NavigateUrl = Sitecore.Links.LinkManager.GetItemUrl(Sitecore.Context.Database.GetItem("path_to_item"));

ASP.NET custom control, can I taking data from a <template> and convert it to a string?

I'm trying to have an asp.net custom control with a field like:
<ErrorTemplate>
<h1>Error</h1>
<p>Blue wizard shot the food</p>
</ErrorTemplate>
What I want to end up with is:
<h1>Error</h1><p>Blue wizard shot the food</p> in a string in my codebehind.
At the moment, the process I use to get this data out of the template is:
First this gets instantiated into a placeholder by my code:
ErrorTemplate.InstantiateIn(errorPHolder);
which is an asp.net placeholder control - it has to be instantiated into something which can support controls.
What I then want to do is add this to my page using JQuery and a variable, like this:
string script = "var Errortemplate = " + errorPHolder.ToString() + ";";
scriptmanager.register(script); // pseudocode
so the result would be, on my page:
var Errortemplate = '<h1>Error</h1><p>Blue wizard shot the food</p>';
Then I can use JQuery to do someDiv.html(Errortemplate);
Finally resulting in whatever they put in <ErrorTemplate> appearing on the page
Because I'm using JQuery it might be possible to do this a different way, such as adding the placeholder to the page into a hidden div and using JQuery to copy the values out.
Any ideas?
Have you tried to render your control?
StringBuilder sb = new StringBuilder();
using (StringWriter tw = new StringWriter(sb))
{
using (HtmlTextWriter hw = new HtmlTextWriter(tw))
{
errorPHolder.RenderControl(hw);
}
}
// its HTML string representation of errorPHolder
string html = sb.ToString();

ASP.NET MVC2: modifying master css property depending on query string parameter

I am migrating a web site to a new one using ASP .NET MVC2.
In the original site, master page has code-behind to check a query string parameter value. Depending on this value, code-behind dynamically modify some CSS property to hide / display master page elements.
As MVC2 has no code-behind because we are supposed to perform everything in the controllers, how should I proceed in this case ?
I see this : asp.net mvc modifying master file from a view
It partially answers my needs but the query string processing is common to all pages. How can I move this processing in a common code section ?
Regards.
A helper method looks like a good place:
public static class HtmlHelperExtensions
{
public static string GetCss(this HtmlHelper htmlHelper)
{
// read some request parameter
// here you also have access to route data so the
// parameter could be part of your custom routes as well
var foo = htmlHelper.ViewContext.HttpContext.Request["foo"];
// based on the value of this parameter
// return the appropriate CSS class
return (foo == "bar") ? "barClass" : "fooClass";
}
}
And somewhere in your master page:
<body class="<%= Html.GetCss() %>">
Or if you are always going to apply it to the body tag only it might be more appropriate to do this in order to reduce the tag soup:
public static class HtmlHelperExtensions
{
public static MvcHtmlString StartBody(this HtmlHelper htmlHelper)
{
var body = new TagBuilder("body");
var foo = htmlHelper.ViewContext.HttpContext.Request["foo"];
var bodyClass = (foo == "bar") ? "barClass" : "fooClass";
body.AddCssClass(bodyClass);
return MvcHtmlString.Create(body.ToString(TagRenderMode.StartTag));
}
}
and in your master page at the place of the body tag:
<%= Html.StartBody() %>
I can think of two solutions to this:
Derive your controllers from one controller base and set the ViewData parameter there depending on posted Form values
Don't use ViewData at all, but simply look for the form value in the view (using HttpContext.Current)
The second method violates the MVC pattern. IMO it is still acceptable in some scenarios, for example I am using this approach to highlight the currently selected item in a navigation menu.

Problem with displaying image from DB using asp.net MVC 2

I'm having trouble with displaying image from db. I think that method for saving image is working, because I see in DB that varbinary fields have some value, and that image type is correct. Also the size of image. But when I want to display image for product i don't get anything. Just blank space.. here is my code...
public byte[] GetImage(int productID)
{
Product product = products.GetByID(productID);
byte[] imageData = product.ImageData.ToArray();
return imageData;
}
That code is in my controller. Second is code from view :
<% if (product.ImageData != null) { %>
<img src='/product/getimage/<%= Html.Encode(product.ID) %>' alt=""/>
<% } %>
I tried some solutions found here on stack overflow, and everyone do it like this, but it's working for them. I dont have any idea why images aren't displayed. When i look at source code of page at debugging i have :
<img src='/product/getimage/18' alt=""/>
I'm using .net 4.0, MVC 2, VS 2010... Thanks in advance
My guess is that you have a routing issue. If the url /product/getimage/18 should work for your action you need to have a route that looks something like this:
routes.MapRoute("ProductImage",
"product/getimage/{productID}",
new { controller = "Product", action = "GetImage", productID = "" }
);
To confirm this you should use firebug and check the "net" tab (or set a breakpoint in your action and see if it gets hit when you load the page).
I would also recommend using the build in helpers to generate your urls (then this kind of problem will never happen). Instead of src='/product/getimage/<%= Html.Encode(product.ID) %>' you can write src='<%=Url.Action("GetImage", "Product", new { productID = product.ID })%>'
I'm not much of an expert on MVC yet - but from what I can see, I think your GetImage function needs to be an Action Method inside your controller, so it'll need to return an ActionResult?
You'll probably need to set the Content-Type header in the response, too.
This guy looks like he knows what he's talking about...
http://blogs.msdn.com/miah/archive/2008/11/13/extending-mvc-returning-an-image-from-a-controller-action.aspx
Try to change you method to:
public void GetImage(int productID)
{
Product product = products.GetByID(productID);
Response.ContentType = "image/jpeg";
Response.BinaryWrite(product.ImageData.ToArray());
}
You have:
<img src='/product/getimage/18' alt=""/>
Normally i'd say an image tag looks like this:
<img src='/product/getimage/18.jpg' alt=""/>
I needed to register routes in my global.cs file like Mathias suggested.
Also i needed to modify action in my controller to this :
public FileContentResult GetImage(int productID)
{
Product product = products.GetByID(productID);
return File(product.ImageData.ToArray(), product.ImageMimeType);
}
I wish thank you all for your fast answers...

Retrieving data from Html.DropDownList() in controller (ASP MVC) | string returned?

I have the following problem:
I have a form in site/banen (currently local running webserver) which is using a SQL database. The link is made using ADO.net and is instantiated in the controller in the following way:
DBModelEntities _entities;
_entities = new DBModelEntities(); // this part is in the constructor of the controller.
Next, I use this database to fill a Html.DropDownList() in my view. This is done in two steps. At the controller side we have in the constructor:
ViewData["EducationLevels"] = this.GetAllEducationLevels();
and a helper method:
public SelectList GetAllEducationLevels()
{
List<EducationLevels> lstEducationLevels = _entities.EducationLevels.ToList();
SelectList slist = new SelectList(lstEducationLevels, "ID", "Name");
return slist;
}
In the view I have the following:
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<!-- various textfields here -->
<p>
<label for="EducationLevels">EducationLevels:</label>
<!-- <%= Html.DropDownList("EducationLevels", ViewData["EducationLevels"] as SelectList)%> -->
<%= Html.DropDownList("EducationLevels", "..select option..")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
Now, the form is rendered correctly when I browse to the create page. I can select etc. But when selected I have to use that value to save in my new model to upload to the database. This is where it goes wrong. I have the following code to do this in my controller:
//
// POST: /Banen/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection form)
{
// set rest of information which has to be set automatically
var vacatureToAdd = new Vacatures();
//vacatureToAdd.EducationLevels = form["EducationLevels"];
// Deserialize (Include white list!)
TryUpdateModel(vacatureToAdd);
// Validate
if (String.IsNullOrEmpty(vacatureToAdd.Title))
ModelState.AddModelError("Title", "Title is required!");
if (String.IsNullOrEmpty(vacatureToAdd.Content))
ModelState.AddModelError("Content", "Content is required!");
// Update the variables not set in the form
vacatureToAdd.CreatedAt = DateTime.Now; // Just created.
vacatureToAdd.UpdatedAt = DateTime.Now; // Just created, so also modified now.
vacatureToAdd.ViewCount = 0; // We have just created it, so no views
vacatureToAdd.ID = GetGuid(); // Generate uniqueidentifier
try
{
// TODO: Add insert logic here
_entities.AddToVacatures(vacatureToAdd);
_entities.SaveChanges();
// Return to listing page if succesful
return RedirectToAction("Index");
}
catch (Exception e)
{
return View();
}
}
#endregion
It gives the error:
alt text http://www.bastijn.nl/zooi/error_dropdown.png
I have found various topics on this but all say you can retrieve by just using:
vacatureToAdd.EducationLevels = form["EducationLevels"];
Though this returns a string for me. Since I'm new to ASP.net I think I am forgetting to tell to select the object to return and not a string. Maybe this is the selectedValue in the part where I make my SelectList but I can't figure out how to set this correctly. Of course I can also be complete on a sidetrack.
Sidenote: currently I'm thinking about having a seperate model like here.
Any help is appreciated.
You can't return an object from usual <SELECT> tag wich is rendered by Html.DropDownList() method, but only string variable could be returned. In your case ID of EducationLevels object will be send to the server. You should define and use one more custom helper method to reconstruct this object by ID.

Resources