change link in text to hyperlink in controller - asp.net-mvc

I'm having trouble converting text to a hyperlink in a controller, then sending it to the view.
So far, I have:
Controller:
foreach (dynamic tweet in Timeline())
{
string text = tweet["text"].ToString();
const string pattern = #"http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\#\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?";
Regex regexCheck = new Regex(pattern);
MatchCollection matches = regexCheck.Matches(text);
for (int i = 0; i < matches.Count; i++)
{
text = string.Format(#"<a href={0}>{1}</a>", matches[i].Value, matches[i].Value);
}
timeline.Add(text);
}
View:
#Html.DisplayFor(model => model.Timeline)
But It keeps displaying the literal text!
Display: <a href=http://t.co/fm0ruxjVXe>http://t.co/fm0ruxjVXe</a>
Could anyone please show me how this is done? I am quite new to MVC.

since you are sending out html already, try
#Html.Raw(Model.Timeline)
Another option is to send out just the url and the text and build the a tag in the view
#Model.Timeline.Text
That will involve changing your timeline property to being an object with two properties, text and url .

The #Html.DisplayFor helpers in Razor automatically encode the output
If you want to just output the content of model.Timeline, try just using Response.Write

Related

Aspose.Words delete line(row) containing a Bookmark

I have a very basic helper method that sets Bookmark's text.
public static Bookmark SetBookmark(this Document doc, string bookmarkName, string value)
{
var bm = doc.Range.Bookmarks[bookmarkName];
if(bm == null)
throw new NullReferenceException(string.Format("Bookmark {0} Not Found!", bookmarkName));
bm.Text = value ?? string.Empty;
return bm;
}
What I need is to remove a bookmark and delete line of text that contains it when a certain condition is met, e.g. when value == null. Any suggestions?
Sample document looks like:
Hello
[Bookmark]
Goodbye
Resulted document after removal:
Hello
Goodbye
Please set the value of Bookmark.Text property to empty string to remove its content and use Bookmark.Remove method to remove the bookmark from the document. Bookmark.Remove method does not remove text inside the bookmark.
I work with Aspose as Developer evangelist.
Please set the value of Bookmark.Text property to empty string to remove its content as shown in following code example. I already shared this in my previous answer.
Document doc = new Document(MyDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];
// Remove the contents of bookmark.
bookmark.Text = "";
doc.Save(MyDir + #"Out.docx");
I work with Aspose as Developer evangelist.

How to index sub-content in Sitecore with Lucene?

I'm using Sitecore 7.2 with MVC and a component approach to page building. This means that pages are largely empty and the content comes from the various renderings placed on the page. However, I would like the search results to return the main pages, not the individual content pieces.
Here is the basic code I have so far:
public IEnumerable<Item> GetItemsByKeywords(string[] keywords)
{
var index = ContentSearchManager.GetIndex("sitecore_master_index");
var allowedTemplates = new List<ID>();
IEnumerable<Item> items;
// Only Page templates should be returned
allowedTemplates.Add(new Sitecore.Data.ID("{842FAE42-802A-41F5-96DA-82FD038A9EB0}"));
using (var context = index.CreateSearchContext(SearchSecurityOptions.EnableSecurityCheck))
{
var keywordsPredicate = PredicateBuilder.True<SearchResultItem>();
var templatePredicate = PredicateBuilder.True<SearchResultItem>();
SearchResults<SearchResultItem> results;
// Only return results from allowed templates
templatePredicate = allowedTemplates.Aggregate(templatePredicate, (current, t) => current.Or(p => p.TemplateId == t));
// Add keywords to predicate
foreach (string keyword in keywords)
{
keywordsPredicate = keywordsPredicate.And(p => p.Content.Contains(keyword));
}
results = context.GetQueryable<SearchResultItem>().Where(keywordsPredicate).Filter(templatePredicate).GetResults();
items = results.Hits.Select(hit => hit.Document.GetItem());
}
return items;
}
You could create a computed field in the index which looks at the renderings on the page and resolves each rendering's data source item. Once you have each of those items you can index their fields and concatenate all of this data together.
One option is to do this with the native "content" computed field which is natively what full text search uses.
An alternative solution is to make an HttpRequest back to your published site and essentially scrape the HTML. This ensures that all renderings are included in the index.
You probably will not want to index common parts, like the Menu and Footer, so make use of HTMLAgilityPack or FizzlerEx to only return the contents of a particular parent container. You could get more clever to remove inner containers is you needed to. Just remember to strip out the html tags as well :)
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
//get the page
var web = new HtmlWeb();
var document = web.Load("http://localsite/url-to-page");
var page = document.DocumentNode;
var content = page.QuerySelector("div.main-content");

not get image path in asp.net mvc controller

I have tried different syntax as belows.
"<img src='../Images/Live news/Actions-arrow-right-icon.png' />" ;
<img src="<%= Url.Content("~/Images/Live news/Actions-arrow-right-icon.png") %>"
I want to add image through controller not view so is these syntex are correct?
This is my full code
dt = Users.Get_Livenews(0, true, "GActive");
for (int i = 0; i < dt.Rows.Count; i++)
{
objExercise = new HomeModel();
objExercise.livenews = Convert.ToString(dt.Rows[i]["livenews_headline"].ToString()) + "<img src='../Images/Live news/Actions-arrow-right-icon.png' />" ;
Horizontal.Add(objExercise);
}
You should get the list of image paths from controller and then iterate the this list at View level. Means dynamically create images for each image path you iterate.
If your view is strongly-typed and controller returns view with model or say list object then using for or foreach loop, you can prepare table or whatever you need.

MVC3 EF Search DB fields but strip HTML

I am using the entity framework with MVC3 and am trying to do a search on a description field but the problem is that description field has HTML in it eg "< div class="section" />". Can i do a funky search that searches only the stuff outside of the HTML tags?
return context.Categories
.Where(i =>
i.Name.Contains(searchText)
&& i.Description.Contains(searchText)
)
Thanks in advance!
Give HtmlAgilityPack a go. It has methods for extracting the text out of an HTML Document.
You basically just need to do the following:
var doc = new HtmlDocument();
doc.LoadHtml(htmlStr);
var node = doc.DocumentNode;
var textContent = node.InnerText;
Or the much less awesome method:
public static string StripHTML(string htmlString)
{
string pattern = #"<(.|\n)*?>";
return Regex.Replace(htmlString, pattern, string.Empty);
}
All together
return StripHTML(context.Categories.Where(i => i.Name.Contains(searchText)&& i.Description.Contains(searchText)))

How to self-redirect and changing a parameter in asp.net mvc?

If my urls looks like:
www.mysite.com/1/home
www.mysite.com/1/other-action
www.mysite.com/1/another-action/?value=a
how can I switch the 1 parameter while invoking the same action with the same parameters and querystring values?
For example if I'm currently browsing
www.mysite.com/1/another-action/?value=a
I would like to obtain the necessary links to switch to
www.mysite.com/2/another-action/?value=a
.
.
www.mysite.com/x/another-action/?value=a
Url.Action seems not to help...
The general idea is clone the current RouteValueDictionary, change one value, and then build a new action link based on the new RouteValueDictionary. Here's an example. But you'd probably want to do this in a URL helper, rather than directly in the view:
<% var foo = new RouteValueDictionary();
foreach (var value in ViewContext.RouteData.Values)
{
foo.Add(value.Key, value.Value);
}
foo["id"] = 2;
var newUrl = Url.Action(foo["action"].ToString(), foo); %>
I would propose small optimization to Craig's answer:
<% var foo = new RouteValueDictionary(ViewContext.RouteData.Values);
foo["id"] = 2;
var newUrl = Url.Action(foo["action"].ToString(), foo); %>

Resources