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.
Related
<div class="container">
#section HeroSection{
#foreach (var category in Model.AllCategory.Where(m => m.IsFeatured).FirstOrDefault().CategoryPictures.Select(m => m.Picture).Distinct())
{
<div class="hero__item set-bg" data-setbg="/FileStore/images/#category.Url">
<div class="hero__text">
<span>FRUIT FRESH</span>
<h2>Vegetable <br />100% Organic</h2>
<p>Free Pickup and Delivery Available</p>
SHOP NOW
</div>
</div>
}
}
</div>
</div>
</div>
}
</div>
I tried to #Render the //#section HeroSection// as false in _layout page .so that it will only appear in home/index ..not in other pages!
I can think of 2 approaches.
the first one is not so practical which is making 2 different layouts, one without the div and one with it. And you can change the layout of the homepage in the razor file like this
#{Layout = "YourNewLayOut"}
The other approach which I think it's better is to use JavaScript.
you can use window.location.href to get the current url and check if it's the url of the home page you target the div and make hidden otherwise visible.
your function should look like this :
function someFunctionName() {
let div = document.querySelector("#yourDiv");
if (window.location.href === "your home page url ") {
div.style.display = "none";
} else {
div.style.display = "block or flex or what ever you're using";
}
}
and then Invoke this function on loading like this
window.onload = function() {
someFunctionName();
};
I'm more familiar with WebForms (which my company uses), and just started learning MVC. I followed the movies tutorial, and am having a bit of a hard time seeing how I can use the MVC pattern the way I want.
For instance, my company often asks me to make web apps that take some input from the user, looks it up in our database, and gives them back some other piece of data pertaining to the input, all on the same page.
With WebForms I can easily see if the database returned null and display an error label in that case. But with MVC treating data access like an API, I don't see how I can do the same thing without ignoring using the proper 404 code. Let's say I want to look up a movie (I commented out the 404s on purpose for now):
public class MoviesController : Controller
{
private readonly MovieDBContext _context;
public MoviesController(MovieDBContext context)
{
_context = context;
}
// GET: Movies/Info/Title
public async Task<IActionResult> Info(string title)
{
//if (title == null)
//{
//return NotFound();
//}
var movie = await _context.Movies
.FirstOrDefaultAsync(m => m.Title == title);
// if (movie == null)
// {
// return NotFound();
//}
return Json(movie);
}
Then in the view:
<h2>App</h2>
<br />
<div class="form-group">
<p>
Price Lookup App
</p>
<br />
<div class="row">
<div class="col-xs-2">
Enter movie title:
</div>
<div class="col-xs-2">
<input type="text" class="form-control" id="title" />
</div>
<div class="col-xs-2">
<input type="submit" class="btn" onclick="getMovie()" />
</div>
</div>
<br />
<div class="row">
<label id="price"></label>
</div>
</div>
<script>
function getMovie() {
var movie = $("#title").val();
if (movie != "") {
$.getJSON("../Movies/Info?title=" + movie, function (response) {
if (response != null) {
$("#price").html(response.price);
}
else {
$("#price").html("Film not found");
}
});
}
else {
$("#price").html("Film not found");
}
}
</script>
This technically works, but I feel I'm really not supposed to do it this way. I should be giving a 404 code when the movie isn't found, correct? I just don't know how to handle getting a 404 response and displaying a custom "not found" message on the same view like I am above, because the 404 stops execution of the JS. Thanks.
You can use $.ajax (ajax call), or $.get(get api call). There are componenets of success and error. you can handle the responses there
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.
so I'm still pretty new in ASP.net MVC design. I am facing a small problem, which might have already been answered, but don't seem to find an answer that will fit my purpose. Here is what's happening:
Say I have a model with 2 links: Category & Item, and it's a 1 to many relation. What I want to do is generate a list containing Category.Title (which I have completed, using the code following) and clicking on the each list item will generate a list of all Item.Title values of that category. The base idea of the html is:
<div id="cat"><!--float = left-->
<ul>
<li>List<li>
</ul>
</div>
<div id="item"> <!--float = right -->
<ul>
<li>List<li>
</ul>
</div>
Here is how everything is linked up so far:
public ActionResult Equipment()
{
ViewBag.Cat= getCat(1); // Will return a list of categories of ID 1
return View();
}
As for the view:
#{ List<X.Models.Category> catX = ViewBag.Cat; }
BODY:
<div id="pl_categories">
<ul id="pl_ec_ul">
#foreach (X.Models.Category item in catX)
{
<li id="pl_ec_li">
<div id="pl_ec_liItem">
#item.catTitle
</div>
</li>
}
</ul>
</div>
<div id="pl_values">
<ul id="pl_ev_ul">
<li id="pl_ev_li">
<div id="pl_ev_liItem">
???
</div>
</li>
</ul>
I have seen a bunch of examples, but they all involve dropdowns or what not. Here are a quick checklist of what I am trying to accomplish:
On page laod, default selected category will be the first in the list. If list is null, a simple "No Categories" is shown. Edit: if the category is empty, it will show No Items in Category.
On clicking an item in the category it will show the items of that category under pl_values.
I have tried to make this is small as possible but there are a lot more factors I need to consider. However, if I can solve this, I am certain to figure out the rest. If something however is not clear, please let me know and I can try and clarify it. Any help will be appreciated. Thank you.
For your item 1, you could try something like this (assuming your OK using jQuery):
$(document).ready(function() {
var count = $("#pl_ec_ul li").length;
if(count <= 0) {
$("#pl_categories").html("<p>No Categories</p>");
}
});
I am confused as to how to implement the following in my current foreach:
#foreach
(var post in Model."table".Where(w => w.Private_ID == 1).OrderBy(o => o.Date))
{
<div class ="post">
<fieldset>
<p class="post_details">At #post.Post_Date By #post.Username</p>
#post.Post_Desc
</fieldset>
</div>
}
so that post.Username will NOT show if #post.anon is TRUE (and so that it will say "Anonymous")
Thanks in advance for any advice/help/suggestions.
You should be able to do something along the lines of:
#(post.anon ? "Anonymous" : post.Username)
Though I would consider doing most of this logic in the C#, rather than leaving it to the view (therefore, creating a specific view model with all of the logic already done. Meaning you can just loop through and not have to do any additional thinking:
#foreach(var post in Model.Posts)
{
<div class ="post">
<fieldset>
<p class="post_details">At #post.Post_Date By #post.Poster</p>
#post.Post_Desc
</fieldset>
</div>
}
Where #post.Poster in the above example is already preset with anonymous if it is required.
Try this:
#foreach(var post in Model."table".Where(w => w.Private_ID == 1).OrderBy(o => o.Date))
{
<div class ="post">
<fieldset>
<p class="post_details">At #post.Post_Date By (#post.Anon == true ? "Anonymous" : #post.Username)</p>
#post.Post_Desc
</fieldset>
</div>
}
EDIT: Sorry, the line should have said: #(post.Anon == true ? "Anonymous" : post.Post_Desc)