Filling Data For Partial View MVC - c#

We're developing news website we're confused with some concept of usage. I'd like to ask and know better if possible. We've a homepage which may contain a lot of models at once so we're separating our homepage to partial views and we're planning to feed them with the appropriate models.
In one partial we're enumerating in categories that are not marked as deleted and we've two types of categories. One of them displays the latest post and the other displays 4 posts at once. We've achieved this actually but as i've mentioned we would like to know if there is a better way or if we're doing anything wrong because right now we're keeping the connection to the context open until the partial is rendered.
Here is the code for views
Partial View Code (CategoryRepeater.cshtml)
#using SosyalGundem.WebUI.DatabaseContext;
#{
var categoryList = new List<PostCategories>();
var db = new SosyalGundemDb();
categoryList = db.PostCategories.Include("Posts").Where(x => !x.IsDeleted).ToList();
}
#for (int i = 0; i < categoryList.Count; i++)
{
if (i % 3 == 0 || i == 0)
{
#Html.Raw("<div class=\"row-fluid spacer\">")
}
var category = categoryList[i];
if (category.PostCategoryType == 1)
{
<div class="span4">
<h3 class="title"><span>#category.PostCategoryName</span></h3>
#{
var article = category.Posts.FirstOrDefault();
if (article != null)
{
<article class="post">
<div class="entry clearfix">
<div class="span6">
<a href="#" title="Permalink to Suspen disse auctor dapibus neque pulvinar urna leo" rel="bookmark">
<img width="225" height="136" src="#Url.Content("~/Content/uploadedimages/" + article.Media.ToList()[0].MediaContent )" alt="shutterstock_70184773" />
</a>
</div>
<div class="span6">
<h4 class="smallnewstitle">#article.PostTitle</h4>
<p>#(article.PostSummary.Length > 100 ? article.PostSummary.Substring(0, 100) : article.PostSummary)</p>
<div class="meta">
<span class="date">#article.PostDate.ToString("MMMM dd, yyyy")</span>
</div>
</div>
</div>
</article>
}
}
</div>
}
else
{
<div class="video-box widget span4">
<h3 class="title"><span>#category.PostCategoryName</span></h3>
#{
int cati = 0;
var firstPost = category.Posts.OrderByDescending(x => x.PostDate).FirstOrDefault();
}
#if (firstPost != null)
{
<h4 class="smallnewstitle">#firstPost.PostTitle</h4>
<p>#(firstPost.PostSummary.Length > 100 ? firstPost.PostSummary.Substring(0, 100) : firstPost.PostSummary) </p>
<ul>
#foreach (var item in category.Posts.OrderByDescending(x => x.PostDate))
{
if (cati <= 3)
{
<li>
<a href="#" title="#item.PostTitle" rel="bookmark">
<img width="225" height="136" src="#Url.Content("~/Content/images/dummy/shutterstock_134257640-225x136.jpg")" alt="shutterstock_134257640" />
</a>
</li>
}
else
{
break;
}
cati++;
}
</ul>
}
</div>
}
if (i % 3 == 0 && i != 0)
{
#Html.Raw("</div>")
}
}
#{
db.Dispose();
}

Separate your concerns. You can see this project for start: http://www.codeproject.com/Tips/617361/Partial-View-in-ASP-NET-MVC
Controller
#using SosyalGundem.WebUI.DatabaseContext;
public ActionResult SomeAction()
{
var model = new CategoriesModel
{
NotDeletedCategories = db.PostCategories.Include("Posts").Where(x => !x.IsDeleted).ToList(),
DeletedCategories = db.PostCategories.Include("Posts").Where(x => x.IsDeleted).ToList()
};
return View(model);
}
Model
public class CategoriesModel
{
public List<PostCategories> NotDeletedCategories {get;set;}
public List<PostCategories> DeletedCategories {get;set;}
};
View
#model CategoriesModel
#Html.RenderPartial("DeletedCategories", Model.DeletedCategories)
#Html.RenderPartial("NotDeletedCategories", Model.NotDeletedCategories)

Hi Jinava,
I would suggest bind Model to the View,
Like,
public ActionResult CategoryRepeater()
{
var multiViewModel = new MultiViewModelModel
{
ModelForParialView1= new XYZ(),
ModelForParialView2= new PQR()
};
return View(model);
}
For the View
#model MultiViewModelModel
And then PAss the views with the MultiViewModelModel.ModelForParialView1 and MultiViewModelModel.ModelForParialView2
You can perform all the model operations on the view.
And at the controller level perform all the database operations and release the database connection there itself no need to get that on the view.
Hope this explanation helps you.

Related

C# MVC System.StackOverflowException

I am getting this error, I believe that it is because I have one two many Html.RenderAction(); on my home page. On top of a few #Html.Partial() My site is fine if I remove the last one I put in. Which is bringing up a list of Operating hours from a table. I have 2 on the footer one to show recent posts and the hours. The Footer is on a Partial page. In total there are Login Partial, Cart Summary -- RenderAction, and Footer Partial on the main Layout page plus of course RenderBody(). The Index page has 2 partials on it so far and was planning on using more. All of these have models to tables attached to them from tables. I get the error on the login Partial and sometimes on the blog posts. If I comment out the one I just made it works fine. And navigating to the page itself works with no errors. At first I had it as a partial page in the shared folder and it just doesn't show up. I have done all of these,
public ActionResult _Hours()
{
var hrs = db.OperatingHours.OrderBy(x => x.SortOrder).ToList();
return PartialView(hrs);
}
public ActionResult Hours()
{
var hrs = db.OperatingHours.OrderBy(x => x.SortOrder).ToList();
return View(hrs);
}
Is there a work around for this?
The issue was as David mentioned above in the comments, I had an infinite loop in my view code. Below is how it originally was written.
<ul class="list-border">
#foreach (var item in Model)
{
<li class="clearfix">
#if (item.SelOpen == true)
{
<span>#if (item.ShowSelect == true)
{<text>Select</text>} #item.Day : </span>
<div class="value pull-right flip"> #item.OpenTime #if (item.ShowBreak == true)
{<text>-</text> #item.BreakTime} - #item.CloseTime </div>
}
#if (item.SelClosed == true)
{
<span> #item.Day : </span>
<div class="value pull-right flip"> Closed </div>
}
</li>
}
</ul>
Below is the code that it was changed to for it to work.
<ul class="list-border">
#foreach (var item in Model)
{
<li class="clearfix">
#if (item.SelOpen == true)
{
<span>#if (item.ShowSelect == true)
{<text>Select</text>} #item.Day : </span>
<div class="value pull-right flip"> #item.OpenTime #if (item.ShowBreak == true)
{<text>-</text> #item.BreakTime} - #item.CloseTime </div>
}
else
{
<span> #item.Day : </span>
<div class="value pull-right flip"> Closed </div>
}
</li>
}
</ul>
I normally code the above way with `if(){ }else{}. And I guess I have done it the other way as well, but not in a foreach loop.. Lesson learned.

Umbraco pagination

First time Umbraco user.
I'm looking to add pagination to the following basic loop:
#foreach (var example in CurrentPage.Children.OrderBy("createDate descending").Take(8)){
//Do Stuff//
}
Any ideas? Thanks
After a good amount of work and research, here is my final code for pagination in umbraco. Replace the examples with your stuff, and pageSize is the amount of posts shown on each page.
#{
var pageSize = 8;
if(Model.Content.HasValue("numberOfItemsPerPage")){
pageSize = Model.Content.GetPropertyValue<int>("numberOfItemsPerPage");}
var page = 1; int.TryParse(Request.QueryString["page"], out page);
var items = Umbraco.TypedContent(Model.Content.Id).Children.Where(x => x.DocumentTypeAlias == "exampleAlias" && x.IsVisible());
var totalPages = (int)Math.Ceiling((double)items.Count() / (double)pageSize);
if (page > totalPages)
{
page = totalPages;
}
else if (page < 1)
{
page = 1;
}
foreach (var item in items.Skip((page - 1) * pageSize).Take(pageSize).OrderBy("createDate descending"))
{
<div class="example-div">
<h2>#item.GetPropertyValue("example")</h2>
</div>
}
if (totalPages > 1)
{
<div class="pagination">
<ul>
#if (page > 1)
{
<li>Prev</li>
}
#for (int p = 1; p < totalPages + 1; p++)
{
<li class="#(p == page ? "active" : string.Empty)">
#p
</li>
}
#if (page < totalPages)
{
<li>Next</li>
}
</ul>
</div>
}
}
Hope this stops a headache for someone.
Phil's answer is great, but I would recommend putting the order on the items variable rather than the foreach - that way if any more complicated sorting is necessary it's being done before the pagination is implemented.
The updated code snippets would be:
#{
var pageSize = 8;
if(Model.Content.HasValue("numberOfItemsPerPage")){
pageSize = Model.Content.GetPropertyValue<int>("numberOfItemsPerPage");}
var page = 1; int.TryParse(Request.QueryString["page"], out page);
var items = Umbraco.TypedContent(Model.Content.Id).Children.Where(x => x.DocumentTypeAlias == "exampleAlias" && x.IsVisible()).OrderByDescending(x => x.CreateDate);
var totalPages = (int)Math.Ceiling((double)items.Count() / (double)pageSize);
if (page > totalPages)
{
page = totalPages;
}
else if (page < 1)
{
page = 1;
}
foreach (var item in items.Skip((page - 1) * pageSize).Take(pageSize)
{
<div class="example-div">
<h2>#item.GetPropertyValue("example")</h2>
</div>
}
if (totalPages > 1)
{
<div class="pagination">
<ul>
#if (page > 1)
{
<li>Prev</li>
}
#for (int p = 1; p < totalPages + 1; p++)
{
<li class="#(p == page ? "active" : string.Empty)">
#p
</li>
}
#if (page < totalPages)
{
<li>Next</li>
}
</ul>
</div>
}
}
My 50 cents
Jeroen Breuer created a github project called Hybrid Framework in which he has added some route hijacking to an umbraco side to do paging and have strongly typed models. Take a look at it and i'm sure you will like it. It also uses caching i believe.
There was also a video about this i saw but i could not find it anymore.
Hope this helps people trying to implement Paging and some other nice stuff to you Umbraco projects.
UPDATE: found the video on GitHub in readme
These are all great answers, especially the pointer to Jeroen Breuer's library, but just in the name of being thorough and talking about all options -- if you are using jquery in your project and if you have relatively small result sets you could also go with a simple front end only solution.
You'd just bind the entire results list and then use a library like JPList (http://jplist.com ) as I have done here. Go to http://www.charterpublic.org/find-a-school/ and type in city Denver for example. You'll see there are 50+ results. I bind the entire results list then use jplist to make it sortable/pageable etc.
#if (results.Any())
{
<div class="list">
#foreach (var result in results.OrderByDescending(r => r.Name))
{
<div class="list-item">
//build your item
</div>
}
</div>
}
<div class="jplist-panel">
<!-- bootstrap pagination control -->
<ul class="pagination text-center jplist-pagination"
data-control-type="boot-pagination"
data-control-name="paging"
data-control-action="paging"
data-range="4"
data-mode="google-like"></ul>
<!-- items per page dropdown -->
<div class="hidden dropdown pull-left jplist-items-per-page"
data-control-type="boot-items-per-page-dropdown"
data-control-name="paging"
data-control-action="paging">
<button class="btn btn-primary dropdown-toggle"
type="button"
data-toggle="dropdown"
id="dropdown-menu-1"
aria-expanded="true">
<span data-type="selected-text">Items per Page</span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdown-menu-1">
<li role="presentation">
<a role="menuitem" tabindex="-1" href="#" data-number="3">3 per page</a>
</li>
<li role="presentation">
<a role="menuitem" tabindex="-1" href="#" data-number="5">5 per page</a>
</li>
<li role="presentation">
<a role="menuitem" tabindex="-1" href="#" data-number="10" data-default="true">10 per page</a>
</li>
<li role="presentation" class="divider"></li>
<li role="presentation">
<a role="menuitem" tabindex="-1" href="#" data-number="all">View All</a>
</li>
</ul>
</div>
</div>
Then at the bottom of your view...
<script type="text/javascript">
$(document).ready(function () {
$('#demo').jplist({
itemsBox: '.list',
itemPath: '.list-item',
panelPath: '.jplist-panel'
});
});
</script>
There are other front end libraries that do this, but I found JPList the easiest to use for me.
The downside is it's not lazy loaded so it's a little heavier, but with smallish lists like mine here this was a great and simple solution.
I know that this is old , I used the Phil code recomendations and works very good.
But all the pages when incresing the pagination buttons works as infinite regeneration, what I mean is how can I do this as example:
Prev 123456789...Next and when is selected the page 5 for example shows like this:
Prev 5 6 7 8 9 10 11 12 13 ... Next and in the inverse or last page like this:
Prev ... 47 48 49 50 51 52 53 54 55
What I mean guys is to have just a 9 pages on click in the pagination buttons, but I need to implement with the same code that Phil Share :
#{
var pageSize = 8;
if(Model.Content.HasValue("numberOfItemsPerPage")){
pageSize = Model.Content.GetPropertyValue<int>("numberOfItemsPerPage");}
var page = 1; int.TryParse(Request.QueryString["page"], out page);
var items = Umbraco.TypedContent(Model.Content.Id).Children.Where(x => x.DocumentTypeAlias == "exampleAlias" && x.IsVisible());
var totalPages = (int)Math.Ceiling((double)items.Count() / (double)pageSize);
if (page > totalPages)
{
page = totalPages;
}
else if (page < 1)
{
page = 1;
}
foreach (var item in items.Skip((page - 1) * pageSize).Take(pageSize).OrderBy("createDate descending"))
{
<div class="example-div">
<h2>#item.GetPropertyValue("example")</h2>
</div>
}
if (totalPages > 1)
{
<div class="pagination">
<ul>
#if (page > 1)
{
<li>Prev</li>
}
#for (int p = 1; p < totalPages + 1; p++)
{
<li class="#(p == page ? "active" : string.Empty)">
#p
</li>
}
#if (page < totalPages)
{
<li>Next</li>
}
</ul>
</div>
}
}
Just to have a limit of 9 pages with the (...) according the page position.
Help!

What can I do to come back to this previous view in C#/.NET?

I am pretty new in C# and .NET MVC framework and I have the following problem.
I have a first JQuery Mobile view that show a navbar containing some tabs. Into one of this tab I putted a ListView that show the element of a collection of DataModel.Vulnerability.Fix objects represented by the Model.VulnerabilityFixes into my model object. On the right of every element of the list I have put a button/link to delete the related Fix object that generate this row in the list.
This work fine and I obtain the following result (I post a screenshot):
This is the code of the previous tab (the one that show the Fix list):
<!-- TAB-2: FIXES, SOLUTION e MITIGATING STRATEGY: -->
<div id="tab-2" class="ui-body-d ui-content">
<h3>Fixes</h3>
<a href="#Url.Action("SearchCPE", "Asset", new { id = Model.Id })" data-icon="plus" data-inline="true" data-mini="true" data-role="button" >Aggungi un Fix</a>
<!-- Tabella contenente la lista delle fix: -->
<ul data-role="listview" data-inset="true" data-theme="b" data-split-icon="delete">
#foreach (DataModel.Vulnerability.Fix item in Model.VulnerabilityFixes)
{
<li><a href="#Url.Action("Details", "Product", new { Title = item.Title })">
<h2>#item.Title</h2>
<table style="width: 100%">
<tr>
<th>Id</th>
<th>FixName</th>
<th>Vendor</th>
<th>Version</th>
</tr>
<tr>
<td>#MyHelper.decodeNull(item.Id)</td>
<td>#MyHelper.decodeNull(item.FixName)</td>
<td>#MyHelper.decodeNull(item.Vendor)</td>
<td>#MyHelper.decodeNull(item.Version)</td>
</tr>
</table>
</a>
Delete
</li>
}
</ul>
</div>
<!-- /tab-2 -->
Ok, now I have a DeleteFix() method into the EditingController class that handle the request generated clicking od the Delete button.
This one:
public ActionResult DeleteFix(long vulnId, int currentFixId, string currentFixName)
{
DataModel.Vulnerability.Fix model = new DataModel.Vulnerability.Fix();
manager.openConnection();
try
{
model.Id = currentFixId;
model.FixName = currentFixName;
}
finally
{
manager.closeConnection();
}
return View(model);
}
This method show another view, the DeleteFix.cshtml file, that show a confirm window where is asked to the user to confirm the delete operation or if come back to the previous page, this is the code:
#model DataModel.Vulnerability.Fix
#{
ViewBag.Title = "DeleteFix";
Layout = "~/Views/Shared/MasterPageMobile.cshtml";
}
<h1>Delete Fix</h1>
<h2>Fix: #Model.Title (id: #Model.Id)</h2>
<p>
Confermare la cancellazione del fix "#Model.FixName" ?
</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<input type="hidden" name="id" value ="#Model.Id" />
<div data-role="controlgrup" data-type="horizontal" data-mini="true">
<a href="#Url.Action("Index", "Editing", new { id = Model.Id })" data-inline="true" data-mini="true" data-role="button" >Torna alla lista</a>
<a href="#Url.Action("Details", "Groups", new { id = Model.Id })" data-mini="true" data-inline="true" data-role="button" >Annulla</a>
<input type="submit" value="Delete" data-mini="true" data-inline="true" />
</div>
}
My problem is that I want that if the user click on the Torna alla lista button it have to be taken to the initial view that show the list of Fix object but I can't do it
Someone can help me to understand what am I missing? What can I do to obtain this result?
Tnx
Basically I would add a new property in the viewmodels used in the secondary views to have a trace of the primary url :
public string BackUrl { get; set; }
Maybe if you want this feature for more that I secondary view, you can create a base view model that all secondary viewmodels inherit.
Then, when calling a secondary view, just initialize the BackUrl property :
Delete
In the end, in the DeleteFix action, redirect to the BackUrl instead of redering the view (if the viewstate is valid :
public ActionResult DeleteFix(long vulnId, int currentFixId, string currentFixName)
{
if (ModelState.IsValid)
{
DataModel.Vulnerability.Fix model = new DataModel.Vulnerability.Fix();
manager.openConnection();
try
{
model.Id = currentFixId;
model.FixName = currentFixName;
}
finally
{
manager.closeConnection();
}
return Redirect(viewModel.BackUrl);
}
// Invalid viewstate, re-render the view
return View(model);
}

Using list in a model value in LINQ query

I am at very basic stage of asp.net MVC development. So sometimes I struggle with simple LINQ queries to work.
scenario-
I have A page that has some Image and comment on that Image by users (Just Like a post on facebook containing comments from users).
So I am saving those comments from the textarea and sending Image ID via Ajax query.
Here Is my controller action method-
Saving comment-
[HttpPost]
public void SaveComment(CardModel card) {
CardCommentTable commenttable = new CardCommentTable();
commenttable.CardComment = card.cardComment;
commenttable.FKcardID = card.cardID;
db.CardCommentTables.InsertOnSubmit(commenttable);
db.SubmitChanges();
}
This Comment is saved in CardCommentTable that has foreign key reference of Table in that Image is saved.
Rendering Image and other fields on view page-
This query renders Image and other fields that make it An Image post. Like title, dateofsubmit, Like etc.
public ActionResult CardDetails(CardModel card) {
var cardDetail = (from u in db.CardTables
where u.CardID == card.cardID
select new CardModel {
cardID = u.CardID,
cardHashCode = u.CardHashCode,
cardDate = u.CardDate,
cardFileName = u.CardFileName,
cardFilePath = u.CardFilePath,
cardTitle = u.CardTitle
}).ToList();
return View(cardDetail);
}
Now In cardTable I have one more column named cardComment in that I want to show all those saved comments from table CardCommentTable.
So I tried-
public ActionResult CardDetails(CardModel card) {
var allsavedcomments= (from u in db.CardCommentTables
where u.FKcardID == card.cardID
select u).ToList();
var cardDetail = (from u in db.CardTables
where u.CardID == card.cardID
select new CardModel {
cardID = u.CardID,
cardHashCode = u.CardHashCode,
cardDate = u.CardDate,
cardFileName = u.CardFileName,
cardFilePath = u.CardFilePath,
cardTitle = u.CardTitle,
cardComment = allsavedcomments // Trying to render all saved coments here.
}).ToList();
return View(cardDetail);
}
View-
#model IEnumerable<FunRanger.Models.CardModel>
#foreach (var item in Model) {
<script type="text/javascript">
$(function () {
$('#save-comment').click(function () {
var textareavalue = $('#textarea-comment').val();
$.ajax({
url: '/Home/SaveComment/',
type: 'post',
data: '&cardComment=' + textareavalue + '&cardID=' + '#item.cardID',
success: function (data) {
$('#all-comments').append(data);
}
});
});
});
</script>
using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#if (Model != null) {
<h2 class="header-wrapmain">
#item.cardTitle
</h2>
#item.cardDate.ToShortDateString()
<img src="#item.cardFilePath" />
<a href="#" class="#item.cardHashCode" rel="tooltip" data-placement="bottom" title="Filter by #item.cardHashCode">
##item.cardHashCode</a>
}
else {
<div class="alert alert-danger">
No More items to preview
</div>
}
}
<textarea class="span12" rows="5" id="textarea-comment" style="resize: none" placeholder="Enter a comment..."></textarea>
Save comment
<ol>
<li>
#item.cardComment
</li>
</ol>
}
How can I insert List result in a column here.
How do I show all saved comments with this above query?
Thanks for any help.
I slightly renovated your code with Foreign key relations ship. This will save your from using two different queries to your database (like what you are doing now).
So if you Database Model looks like this -
Then you should have one viewmodel in your code in this way -
public class ImageViewModel
{
public string ImageId { get; set; }
public string ImageUrl { get; set; }
public List<string> Comments { get; set; }
}
And your controller action which will return all the results should be like this -
public class ListController : Controller
{
public ActionResult Index()
{
ImageViewModel model;
using (SampleEntities entities = new SampleEntities())
{
model = (from p in entities.Images
where p.ImageId == "1"
select new ImageViewModel()
{
ImageId = p.ImageId,
ImageUrl = p.ImageUrl,
Comments = p.ImageComments.Select(pa => pa.Comment).ToList()
}).FirstOrDefault();
}
return View(model);
}
}
Finally the view which will display all the Image results -
#model MVC.Controllers.ImageViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
<h4>ImageViewModel</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.ImageId)
</dt>
<dd>
#Html.DisplayFor(model => model.ImageId)
</dd>
<dt>
#Html.DisplayNameFor(model => model.ImageUrl)
</dt>
<dd>
#Html.DisplayFor(model => model.ImageUrl)
</dd>
<br/>
#foreach (var item in Model.Comments)
{
#item <br/>
}
</dl>
</div>
Output would be -
Your cardComment property is a list of strings; it needs to be iterated in order to be displayed. Replace:
<ol>
<li>
#item.cardComment
</li>
</ol>
with:
<ol>
#foreach (var singleComment in Model.cardComment)
{
<li>#singleComment </li>
}
</ol>

Conditionally change CSS class in Razor view

I need to change the CSS class of the <div> tag with the 'forumChild' class. It has to change every 3 loops of the foreach loop.
Is there a way to do this from within the control?
<div class="Forum">
<p>The Forum</p>
#foreach (var item in Model)
{
<div class="ForumChild">
<img src="#item.Blog.Image.img_path" alt="Not Found" />
<br />
#foreach (var comment in item.Blog.comment)
{
var db = new ACapture.Models.ACaptureDB();
var Name = from p in db.Profile.AsEnumerable()
where (p.AccountID == comment.AccountID)
select p;
<section>
<div>
<a href="#Url.Action("Index", "Home")">#foreach (var y in Name)
{ #(y.FirstName + " " + y.LastName + ":");
}</a>
</div>
<div>
#comment.Commentation
</div>
</section>
}
</div>
}
</div>
Thanks in advance
#{
int counter=0;
}
#foreach (var item in Model)
{
counter++;
<div class="#(counter<=3 ? "classRed":"classBlue")">
<img src="#item.Blog.Image.img_path" alt="Not Found" />
//other markup also here
</div>
if (counter == 6)
{
counter = 0;
}
}
Where classRed and classBlue are the CSS classes
How we handle this issue:
1) you need to create helper method that will return css class by some code.
string GetDivClass(int code)
{
var classes = new [] {"first", "second", "third"};
return classes[code];
}
2) create counter/index and increment it in the loop each time.
3) invoke helper method like GetDivClass(index % 3) at the div element.
PS
It is only POC, so don't use it in a real application (you need to add a validation logic and move 'classes' initialization to another place).
You can write any code you like into a Razor view, so to do what you're thinking of, you could do something like this (I left out most of the inner stuff):
#{
var className = "ForumChild";
}
<div>
#for (int i = 0; i < Model.Count; i++)
{
var item = Model[i];
if (i % 3 == 0)
className = GetNewClassName(); // Or whatever
<div class="#className">
</div>
}
</div>
You can add a counter variable to will start with 1 and increment in loop. Check with if statement is true by % and change the class name
#{ int counter = 1;}
#foreach (var item in Model)
{
if( (counter % 3) ==0 )
{
<div class="ChangedName">
}
else
{
<div class="ForumChild">
}
i++;

Categories