Getting StackOverflowException on RenderSection & ViewBag - c#

It seems that the ViewBag.Title & #RenderSection(..) executes multiple times but i can't figure why it happens
this is a new project, i have just implemented a single controller with a single view
the Index.cshtml contains
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
and the layout:
Thanks in advance :)

Buried beneath your screenshot I can perceive the root of your problem:
<a href="#Html.Action("Inde........
<img src="~/Content/ima....
</a>
You wanted to use Url.Action and not Html.Action which is something entirely different.
<a href="#Url.Action("Inde........
<img src="~/Content/ima....
</a>

Related

ASP.Net Core | Issue with Html.ActionLink

I'm new to ASP.net core and I was trying to write a redirect action using #Html.ActionLink
Here is my code :
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h2>Main Navigation</h2>
<ul>
<li>#Html.ActionLink("PRIVACY PAGE", "Privacy", "Privacy")</li>
</ul>
</div>
This action link is supposed to redirect to the PrivacyPage, but instead, the values that I pass are being sent as a parameter to the URL
https://localhost:7020/?action=Privacy&controller=Privacy
The expected result is
https://localhost:7020/Privacy
Not sure what I'm missing. Will this ActionLink work only for the MVC projects?
Thank You !!
If i understand you correctly, I think you put wrong controller name.
#Html.ActionLink("link text", "actionname", "controllername")
Instead of #Html.ActionLink("PRIVACY PAGE", "Privacy", "Privacy") it will be #Html.ActionLink("PRIVACY PAGE", "Privacy", "Home")
You can use asp-page attribute with Razor Pages.
<a asp-page="/Privacy">Privacy</a>
if your Privacy page in another folder like /Pages/Home/Privacy
<a asp-page="/Home/Privacy">Privacy</a>
For more documentation https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-6.0

Razor Pages: How to include pagesection in a partial page?

I have a Razor Pages layout page that includes a nav bar as a partial page
<html>
...
<body>
...
<partial name="_Nav" />
Inside my _Nav.cshtml
<div class="links">
link 1
link 2
<!-- custom links that are set by each page go here-->
</div>
This layout is used by every page in the website. I would like to be able include "extra" links that pertain to each page in the website.
I've tried doing it was #RenderSection, but it seems that sections are only allowed in the Layout page. Does this mean I need to do away with my _Nav partial and and lump all the code into one file? Or is there a way to keep an organized code structure and still pass some code around? With jinja2 code blocks this is no problem, so I'm hoping there is a nice way in Razor Pages as well!
Also, I really don't want to pass full html strings from the c# class out to the html, I'm already passing out any variables I need in the links.
Thanks for your help!
You don't have to store html in your ViewDataDictionary.
On every view that has extra links to add, store a List<string>, strings being urls, something like this:
View:
#{
ViewData["Links"] = new List<string>(){ "https://www.google.com", "https://www.facebook.com" };
}
Then in your Layout view:
<partial name="_Nav" view-data="#ViewData" />
Now in your partial view:
//Default Links
#if (ViewData["Links"] != null)
{
//We have extra links
List<string> links = (List<string>)ViewData["Links"];
foreach (string link in links)
{
link1
}
}
RenderSection can only be called from a layout page.
There is no such plugin to add the dynamic link to the partial view.
As a workaround,you could put a div outside the _Nav.cshtml like below and use RenderSection to dynamic add link to the div:
....
<div class="links">
<partial name="_Nav" />
#RenderSection("Html", required: false)
</div>
....
_Nav.cshtml:
link 1
link 2
Test View:
#page
#model IndexModel
//do your stuff...
#section Html
{
<a href='#link3'>link3</a>
}

New to MVC can't get layout to work as desired

I am trying to implement what I think is a pretty standard "dashboard" layout. The trick is I know ASP.NET but not so familiar with MVC so this is a learning project.
I have read many an article and they have helped me progress right to the point where I am very stuck and confused.
Part of my confusion comes from an existing advanced MVC project that I am familiar with from a user perspective. This helps in that I am able to pick through the source code and match up what I am learning to what I have seen from the user perspective.
This is not the problem just an example...
For example I read here what I believe is a very good introduction to the concepts. (http://www.codeproject.com/Articles/383145/RenderBody-RenderPage-and-RenderSection-methods-in)
In the MVC project I get to pick through however I see in the _Layout
#if (IsSectionDefined("statusbar"))
{
#RenderSection("statusbar")
}
however #section statusbar is not defined in the _Layout. If I do a global search for #section I find this:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section header
{
}
#section headermenu
{
}
#section statusbar
{
}
#RenderBody()
So am I correct in guessing that statusbar is defined but it is an empty shell?
If it is an empty shell how does it get populated...cause when the project is running the statusbar does indeed have information???
So again this isn't my problem it is just an example of how the information at hand is confusing me.
This IS the problem:I'm not sure when to use PartialView, RenderSection...etc
My layout renders goofy. What is goofy? The only thing I can think of is to show you a screenshot of what happens.
What I want...
Here is the code used to generate these pages. The tags etc. for bootstrap etc. are omitted for brevity.
_Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<title>#PageTitle</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
Header Stuff
</div>
</div>
<div class="row">
<div class="col-md-4">
#RenderBody()
</div>
<div class="col-md-8">
Main Content
</div>
</div>
<div class="row">
<div class="col-md-12">
Footer Stuff
</div>
</div>
</div>
</body>
</html>
Index.cshtml
#model DashboardModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="col-md-1">
<nav id="Navbar" class="navbar navbar-left" role="navigation">
<div id="organizer">
#(Html.Kendo().PanelBar()....etc....)
</div>
</nav>
</div>
<div class="col-md-3">
This is a place holder for my subnav...????
</div>
Stuff1Link cshtml
#model StuffModel
<div style="height:400px; border:dashed; border-width:thick;">
#{ Html.Kendo().MobileLayout().Name("mlay_PropStatus"); }
#(Html.Kendo().MobileView().....
</div>
Seems like layout is not put in Stuff1Link.cshtml
Can you put it like,
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
1.If your view just has some Html code just use "PartialView" :
#Html.Partial("_theLastPost")
2.If your view has controller for passing data it's better use "RenderAction":
#{ Html.RenderAction("_theLastPost"); }
and its controller
public PartialViewResult _theLastPost()
{
var a = (from c in db.Posts
orderby c.ID_Post descending
select c);
return PartialView(a);
}
3.I do not use render section . For more information about RenderSection go asp.net mvc layouts and sections with razor
I've got a post on my blog that discusses some of this you might want to check out.
The layout code you're referencing doesn't make much sense. The only purpose to declaring an empty section, really, is to fulfill a requirement that it exists, when you don't want to actually pass anything there. Since the layout is what defines whether it must be present or not, it makes no sense for it to exist there, empty. More than that, if you implement a section in your base layout, you'll get a runtime error because there's no place higher in the view chain where it's defined.
Long and short, to provide a place holder in your layout for a section you use:
#RenderSection("SectionName", [true|false])
The boolean param indicates whether views that utilize this layout must implement the section; false means it's optional, while true means it's required.
To implement a section in a view, you use:
#section SectionName
{
...
}
If you have a layout that inherits from another layout, that layout must implement all required sections in the layout it inherits from. If you want the the section to be available to views that utilize the sub-layout, you must redefine the section in the section implementation:
_Layout.cshtml
#RenderSection("Foo", true)
_SubLayout.cshtml
#{ Layout = "Views\Shared\_Layout.cshtml"; }
#section Foo
{
#RenderSection("Foo", true)
}
Finally, as to partial views vs. sections, it all comes down to whether you want to insert something into the layout or the view. For example, sections are most commonly used for inserting link tags to CSS files in the head or script tags before the closing body tag, where the view itself would not be able to touch directly. However, it's almost an apples and oranges comparison. Partials can be utilized in the layout, in the view, or even in a section. Whereas, sections can only be utilized in the layout.

MVC 4 - how do I pass model data to a partial view?

I'm building a profile page that will have a number of sections that relate to a particular model (Tenant) - AboutMe, MyPreferences - those kind of things. Each one of those sections is going to be a partial view, to allow for partial page updates using AJAX.
When I click on an ActionResult in the TenantController I'm able to create a strongly typed view and the model data is passed to the view fine. I can't achieve this with partial views.
I've created a partial view _TenantDetailsPartial:
#model LetLord.Models.Tenant
<div class="row-fluid">
#Html.LabelFor(x => x.UserName) // this displays UserName when not in IF
#Html.DisplayFor(x => x.UserName) // this displays nothing
</div>
I then have a view MyProfile that will render mentioned partial views:
#model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
#Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml",
new ViewDataDictionary<LetLord.Models.Tenant>())
</div>
</div>
If I wrap the code inside the DIV in _TenantDetailsPartial inside #if(model != null){} nothing gets displayed on the page, so I'm guessing there is an empty model being passed to the view.
How come when I create a strongly typed view from an ActionResult the user in the 'session' gets passed to the view? How can pass the user in the 'session' to a partial view that is not created from an ActionResult? If I'm missing something about the concept, please explain.
You're not actually passing the model to the Partial, you're passing a new ViewDataDictionary<LetLord.Models.Tenant>(). Try this:
#model LetLord.Models.Tenant
<div class="row-fluid">
<div class="span4 well-border">
#Html.Partial("~/Views/Tenants/_TenantDetailsPartial.cshtml", Model)
</div>
</div>
Also, this could make it works:
#{
Html.RenderPartial("your view", your_model, ViewData);
}
or
#{
Html.RenderPartial("your view", your_model);
}
For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread
I know question is specific to MVC4. But since we are way past MVC4 and if anyone looking for ASP.NET Core, you can use:
<partial name="_My_Partial" model="Model.MyInfo" />
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
#{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
#{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two
Pass Through ViewBag
#{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three
pass through model
#{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}

Umbraco mvc, rendering partial view cannot be resolved to a type

I have a partial view located in ~/Views/Partials/menubar.cshtml .
In my ~/Views folder i have a master page Called Menubar.cshtml <- this masterpage calls the
#{ Html.RenderPartial("menubar") } but it says:
"Cannot resolve partial view "menubar"
How can i fix this? I've tried the direct path like
#{ Html.RenderPartial("~/Views/Partials/menubar.cshtml") } still the same issue.
It has to be said that im using Umbraco 4.11 and Visual studio 2012 with resharper.
Here is the code for my masterpage (it has another masterpage):
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#{
Layout = "Master.cshtml";
}
<div id="header">
<img src="/images/logo.gif" width="259" height="65" />
<div id="sitedescription">
<h1>Runway</h1>
<h1>Off to a great start</h1>
</div>
#{ Html.RenderPartial("Menubar"); }
</div>
#RenderBody()
This is the code for my view, simplified just to get it working at first, there will be added some logic, otherwise the view would not make sense to have:
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
<div id="mainmenu">
<ul id="topNavigation">
<li class="home current">Home</li>
<li><a class="navigation" href="/"><span>Newz</span></a></li>
<li><a class="navigation" href="/"><span>Programmering</span></a></li>
<li><a class="navigation" href="/"><span>Support</span></a></li>
<li><a class="navigation" href="/"><span>Repair</span></a></li>
</ul>
</div>
<div class="mainmenucorner"> </div>
Here is an image of the structure in visual studio:
Can anyone tell me what i'm missing here, have spend hours on this now.
EDIT
I've found out that id i locate it under /Views/Shared it'll find it automatically.. It just seems that umbraco posts this page as the main page then - any thougts?
Try renaming the partial to _menuBar.cshtml, and render it using this:
#Html.Partial("_menuBar")
It works for me.

Categories