hoChay hoChay - 1 month ago 16
ASP.NET (C#) Question

In Sitecore output a link tag in View

In Sitecore I have a controller rendering, which dynamically loops through all of the navigation bar items in the Multi-list and outputs them out to the View.

I have tried the code below:

<li class="first-child"><a href="@i.Url">@i.Name</a></li>


However, when I do inspect element in the Browser this appears:

<a href="<link linktype="external"; url="";https://www.example.com/en-gb/london/eat"; anchor="" target="" />">Eat</a>


The above line produces an additional > before Eat. What do I have to

I have also tried this syntax in the View:

<li class="first-child">
<a href="@Html.Sitecore().Field("Url", i);">
@Html.Sitecore().Field("Name", i);
</a>
</li>


When I inspect element in the Browser I get this:

<a href=";"> ; </a>


I need help rendering this in the View any help with the syntax will be greatly appreciated.

Edit

My Controller action method looks like this below:

public ActionResult FooterCities()
{

var model = new List<FooterCities>();

var footercitycategories = Sitecore.Context.Item;

var item = (Sitecore.Data.Fields.MultilistField)footercitycategories.Fields["FooterCities"];

foreach (var m in item.GetItems())
{
model.Add(
new FooterCities()
{
Name = m["Name"],
CityUrl = m["CityUrl"]
});

}

return View("/Views/Example/Layouts/LayoutRenderings/ViewRendering/FooterCities.cshtml", model);

}

Answer

Try something like this:

@Html.Sitecore().BeginField("Url", new { haschildren= true })
@Html.Sitecore().Field("Name")
@Html.Sitecore().EndField()

Code above copied from another SO answer explaining how to use text field inside a link field here: http://stackoverflow.com/a/32848931/157833 .

or another option:

@Html.Sitecore().Field("Url", new {text = @Html.Sitecore().Field("Name")})

explained by Jason here: https://theagilecoder.wordpress.com/2014/10/06/sitecore-mvc-editable-links-wrapping-text-and-images/

Assuming that you're i is an object of the Item class, you should pass it as a second parameter. Method definition is:

public virtual HtmlString Field(string fieldName, Item item, object parameters)

so in your case it should be:

@Html.Sitecore().Field("Url", i, new {text = @Html.Sitecore().Field("Name")}) 

EDIT after you showed code of your controller

You should change the way of model generation. Use:

foreach (var m in item.GetItems())
{
    Sitecore.Data.Fields.LinkField urlField = m.Fields["CityUrl"];
    string url = urlField.GetFriendlyUrl();
    model.Add(
    new FooterCities()
    {
        Name = m["Name"],
        CityUrl = url
    });
}

and then in the view:

<li class="first-child">
    <a href="i.CityUrl">
        i.Name
    </a>
</li>
Comments