I am trying to parse multiple page IDs into a cookie in Umbraco Razor.
I have this piece of code
#{
var siteroot = Model.AncestorOrSelf(1);
HttpCookie eventCookie = new HttpCookie("eventCookie");
}
#foreach (var child in siteroot.Descendants("Event").OrderBy("Date"))
{
if (DateTime.Today <= child.Date)
{
#RenderPage("~/macroscripts/RenderEventBox.cshtml", child, false)
}
}
#{
Response.Cookies.Add(eventCookie);
}
What I want to do is to create a CSV string in the foreach, with page IDs.
The page IDs should then be inserted in a cookie in which I can check for new IDs since the last time the user visited - for a "This is the new pages since your last visit" functionality.
But I am not sure how to do this.
The outcome that I want should look like
2525,4587,4789,4790,5858,5782,7899
which I then can put into a cookie.
Got it solved quite simple with
#{
var csv = "";
}
#foreach (var child in siteroot.Descendants("Event").OrderBy("Date"))
{
csv += "," + #child.Id;
}
Related
I am trying to display the values of this list of arrays, the problem is that the values are not displaying in the browser. I have the values of the list/arrays.
I don't know the problem or what's wrong with the syntax, any advice?
#{
List<string[]> validate_rules = new List<string[]>();
if (TempData["verification_errors"] != null)
{
validate_rules = (List<string[]>)TempData["verification_errors"];
}
}
#foreach (var item in validate_rules)
{
<label >#item[0].ToString() #item[2].ToString()</label>
}
You've surrounded the entire thing in a Razor Code Block. From the documentation:
Unlike expressions, C# code inside code blocks is not rendered.
I'm surprised it's even syntactically valid with the inline HTML inside a code block like that, unless there's an error that you're just ignoring. Remove the output from the code block. Something like this:
#{
List<string[]> validate_rules = new List<string[]>();
if (TempData["verification_errors"] != null)
{
validation_rules = (List<string[]>)TempData["verification_errors"];
}
}
#foreach (var item in validation_rules)
{
<p>#(item[0].ToString() + " " + item[2].ToString())</p>
}
The output can probably even be simplified to this:
#foreach (var item in validation_rules)
{
<p>#item[0] #item[2]</p>
}
My question would be complicated but I will try to ask clearly.
I want to keep tags in a data at SQL, as using the comma in a cell. Then, try to call two different way on my MVC 4 project. One way (basic one) is working. But another one is hard to run. I will give my codes one by one.
SQL Table:
Controller:
public ActionResult Portfolio()
{
return View(db.Portfolios.ToList());
}
View:
#model IEnumerable<emirhanozkan.Models.Portfolio>
#{
foreach (var pot in Model)
{
<p>#pot.Tags.Split(',')[0]</p>
<p>#pot.Tags.Split(',')[1]</p>
<p>#pot.Tags.Split(',')[2]</p>
}
}
In same View one more foraech is running:
#foreach (var po in Model)
{
<li class="item #po.Tags.ToLower().Trim().Replace(",","")">
<img src="#po.Image" />
#po.Title
</li>
}
So, What I want to do with Split method:
<p>AngularJS</p>
<p>MVC</p>
<p>C#</p>
<p>Wordpress</p>
<p>MVC</p>
I guess my #pot.Tags.Split(',')[0], #pot.Tags.Split(',')[1] and #pot.Tags.Split(',')[2] code is wrong to list them but my brain not working anymore than that one. Please help me get them like my dream. Also, if you now to get just one from repeat words like <p>MVC</p> <p>MVC</p>, to just <p>MVC</p> please add to new code.
You can just loop on the array returned by Split() method and then render the tags:
foreach (var pot in Model)
{
var tags = #pot.Tags.Split(',');
foreach(var tag in tags)
{
<p>#tag</p>
}
}
sorry for errors, I write without compile:
List<Portfolio> Model = new List<Portfolio>();
StringBuilder finaltags= new StringBuilder();
foreach (var pot in Model)
{
finaltags.AppendLine("<p>" + #pot.Tags.Split(',') + "</p>");
}
#Html.Raw(finaltags.ToString());
foreach (var pot in Model)
{
var tags = #pot.Tags.Split(new []{','}, StringSplitOptions.RemoveEmptyEntries);
foreach(var tag in tags)
{
<p>#tag</p>
}
}
foreach (var pot in Model)
{
<li>
<img src="#po.Image" />
<a href="#po.Url" target="_blank" class="md-button md-primary">
#po.Title</a>
</li>
}
Thank you for your suggestions. But I found the answer to my question:
#{
foreach (var pot in Model)
{
string str = pot.Tags;
string[] strT = str.Split(',');
foreach (var poo in strT) {
<p>#poo</p>
}
}
}
This one is very difficult for me to word, which is what is failing me in my google searching, i brand new to asp.net and it's giving me some difficulties with the logic of this requirement
I have a bunch of results which are displayed primarily as images with some text overlayed.
I have some HTML that is required to show these images, but it uses custom styling to show each "row" of images, it uses div's for a custom look.
What i'm needing to do, is work out a way in the cshtml file display a html block to start a row, and then output the html for 6 of the items, then close off that row and begin another one and rinse repeat until completed, but i cannot for the life of me work out how i would go about that in asp.net.
This might be a very very simple issue, but due to my inability to word this correctly for google, I'm really struggling to find anything online.
The closest visual example i can think of is something like Netflix, but without the ability to scroll the movies, so all the movies are listed in those rows.
i'm currently using the following method,
#foreach (var item in Model)
{
html...
}
My original thought was to have a counter and do a conditional statement when the count hit's six, closing the row and starting a new one, but i cannot work out how to mix that much html into code blocks.
#{
int count = 0;
foreach(var item in model)
{
count++;
//Output current item's html
if(count == 6)
{
//End current row, start new row
count = 0;
}
}
but as i mentioned, i can only find how to mix single html elements in with code blocks using the #: method, and i need a block of html.
Adding my controller code as requested, I have it kinda working using viewbag, but the groupedModel seems to split each movie into a separate row.
// GET: Movies
public ActionResult Index(string movieGenre, string searchString)
{
var GenreList = new List<string>();
var GenreQry = from d in db.Movies
orderby d.Genre
select d.Genre;
GenreList.AddRange(GenreQry.Distinct());
ViewBag.movieGenre = new SelectList(GenreList);
var movies = from m in db.Movies
select m;
if(!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
if(!string.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}
var groupedModel = movies.AsEnumerable().Select((e, i) => new { Element = e, Index = i }).GroupBy(e => e.Index % 6).Select(g => g.Select(e => e.Element));
ViewBag.grouped = groupedModel;
return View(movies);
}
and my view (With most of the HTML removed for ease of reading):
#model IEnumerable<MvcMovie.Models.Movie>
#{
ViewBag.Title = "Index";
}
<p>
#Html.ActionLink("Create New", "Create")
#using (Html.BeginForm("Index", "Movies", FormMethod.Get))
{
<p>
Genre: #Html.DropDownList("movieGenre", "All")
Title: #Html.TextBox("SearchString")
<input type="submit" value="Filter" />
</p>
}
</p>
#foreach(var group in ViewBag.grouped)
{
<div class="MovieRow">
#foreach (var item in group)
{
<div class="bob-title">#Html.Display((item as MvcMovie.Models.Movie).Title)</div>
}
</div>
}
EDIT:
The only problem i have left now, is that i can't seem to get the item variables to output, none of the #Html.Display((item as MvcMovie.Models.Movie) sections output anything.
First, let's group your model to get groups with 6 elements (better to do it in the controller, not in the view):
var groupedModel = Model.Select((e, i) => new { Element = e, Index = i })
.GroupBy(e => (e.Index - 1) / 6)
.Select(g => g.Select(e => e.Element));
than you will iterate these group and display them:
#foreach(var group in groupedModel)
{
<div id="rowDiv">
#foreach(var element in group)
{
<div id="elementDiv">// element div here
// display element info here
</div>// element div end
}
</div> // row div end
}
I have news posts within a news page within a homepage on my content structure
Example:
Homepage
- News
-- News Posts
I'm looking to have some of the news feed on my homepage in a foreach statement. In my head it should be as simple as:
#foreach (var homenews in CurrentPage.Children.Children)
{
if (homenews.Name == "News Post")
{
//Do some stuff//
}
}
Obviously that doesn't work so has anybody got any ideas? Thanks
When you're walking the tree you have to remember that a property (or method) like Children or Descendants() will return a collection of objects, so you can't just call Children of a collection. You can only call Children on a single object.
You can find the correct child of the homepage by using something like var newsPage = CurrentPage.Children.Where(x => x.DocumentTypeAlias == "NewsListingPage") and then extract the children of that page.
I ended up getting the news page by its id and then getting it's children from there. The below code worked for me. Thanks guys.
#{
var node = Umbraco.Content(1094);
<p>#node.Id</p> // output is 1094
foreach (var item in node.Children.Where("Visible").Take(3))
{
<p>#item.exampleText</p>
}
}
You need to reference the required node by NodeTypeAlias of it's Document Type.
So assuming the alias of the DocType of your News Posts is “NewsPosts” then...
#foreach (var homenews in #Model.Descendants().Where("NodeTypeAlias == \"NewsPosts\"")).Take(3)
{
<p>#homenews.Name<p>
}
...should return the name of the first 3 news posts.
I had the exact scenario, this is how I got mine working. NodeByID was very useful nad -1 indicates the root
#foreach(var item in Model.NodeById(-1).Children)
{
string itemName = item.Name;
switch(itemName)
{
case "News":
#* News *#
<div id="News">
<h3>#item.Name</h3>
#foreach (var newsPost in item.Children.OrderBy("UpdateDate desc").Take(4).Items)
{
<p>
#newsPost.Title
</p>
}
</div>
}
}
Is possible to get pages which were created by user in umbraco cms. For example my username is admin, and I want to get list all of pages which were created by me using c# code (page name and page url).
It is possible and pretty straight forward. Here are a couple of examples (I'm using razor to spit out the values, but this could easily be put into a user control, or written out to a file or whatever):
Using DynamicNode:
#{
var userId = 0; //admin
var root = Library.NodeById(-1);
var nodes = root.Descendants().Where("CreatorId == #0", userId);
foreach (var node in nodes)
{
#:#node.Id, #node.Name, #node.Url<br />
}
}
Using NodeFactory and uQuery:
#{
var userId = 0; //admin
var root = new Node(-1);
var nodes = root.GetDescendantNodes(n => n.CreatorID == userId);
foreach (var node in nodes)
{
#:#node.Id, #node.Name, #node.Url<br />
}
}
Just replace 0 withe the Id of your user.