I use a sidebar on my website with stats from my database and statics data like links and other texts.
In my _Layout.cshtml, I use Html.RenderAction("SidebarPV", "Home"); to call the sidebar.
The sidebar is a Partial-View using a ViewModel for the stats.
SidebarPV is generated in my HomeController like that :
public ActionResult SidebarPV() {
SidebarViewModel viewmodel = new SidebarViewModel();
DateTime now = DateTime.Now;
viewmodel.stat_data1 = db.Table1.Where(e => e.DateDeb <= now && e.DateFin >= now).Count();
viewmodel.stat_data2 = db.Table2.Where(c => c.DateDeb <= now && c.DateFin >= now).Count();
return PartialView("SidebarPV", viewmodel);
}
It works like a charm but I don't need stats on all views, only on /Home/Index
So I want to 'comment' the stats generation when the ser is not on the index of the website.
Thanks for advices.
EDIT (solution, thanks to krillgar) :
I wrote in my _Layout
#{
var isHome = ViewContext.RouteData.Values["controller"].ToString().ToUpper() == "HOME";
var isIndex = ViewContext.RouteData.Values["action"].ToString().ToUpper() == "INDEX";
if (isHome && isIndex) {
Html.RenderAction("SidebarPV", "Home");
}
else {
Html.RenderAction("SidebarNoStatPV", "Home");
}
}
I know I need to create two partial-views but one is static so I will not edit it for a long time :).
Tested, It works.
There's also another solution. As for me, i hate things like this
ViewContext.RouteData.Values["controller"].ToString().ToUpper() == "HOME"
It has to work with magic strings, which is not even a const, just runtime string. It may provide some issues in advance. And what if you will need it on some another page?
I'd recommend you to use nested layouts. You can create _Layout with section
UPDATE:
_Layout.cshtml:
<...>
#Html.RenderSection("sidebar", false)
<...>
And then on your home page you may just use _SidebarLayout instead of _Layout. And whenever you will need sidebar on any page, you can do just the same.
So your home page will look like
#{
Layout = "~/Views/_Layout.cshtml";
}
#section sidebar {
#Html.RenderAction("SidebarPV", "Home")
}
And all other pages will look like
#{
Layout = "~/Views/_Layout.cshtml";
}
#section sidebar {
#Html.RenderAction("SidebarNoStatPV", "Home")
}
If you don't want to repeat yourself with this "SidebarNoStatPV" you can use nested layouts:
_NoStatLayout.cshtml
#{
Layout = "~/Views/_Layout.cshtml";
}
#section sidebar {
#Html.RenderAction("SidebarNoStatPV", "Home")
}
and use it as the layout for any page but Home. If you will need to extend sidebar with additional info for different pages you can just put #Html.RenderSection("sidebar", false) inside sidebar section in _NoStatLayout.cshtml.
Why do i consider it as a better option? It fits the SRP, for only Home page should be responsible for it's own unique data.
If you want to keep the code to call the action in the _Layout page, then you just need to get information of what action is being called when generating the page. Add the following to the top of your _Layout:
var isHome = ViewContext.RouteData.Values["controller"].ToString().ToUpper() == "HOME";
var isIndex = ViewContext.RouteData.Values["action"].ToString().ToUpper() == "INDEX";
Then wrap your call to generate the partial view wherever you need it in _Layout with the following:
if (isHome && isIndex) {
Html.RenderAction("SidebarPV", "Home");
}
Related
I'm trying to create paging inside html form.
How do I make each page button change the model's CurrentPage property?
I'm new to MVC, so bear with me please.
I have a list of reports that I need to display in a view named Search. I made a model for that (ReportViewModel), and another model that holds a list of those, named SearchViewModel. In SearchViewModel I have some other variables like SearchName, SearchDate, CurrentPage, PageCount, PageSize, etc. The goal is to do paging and searching in one action named Search in ReportsController.
Now, I would like to keep that action simple by giving that function only SearchViewModel instance as a parameter, so that inside I use all variables of that model. Doing that, I won't have to type parameter names twice (once in SearchViewModel and once as parameters in Search action). I will not need that search function elsewhere, so it's ok for it to not have any parameters other than SearchViewModel instance.
So, very loosely, it looks something like this:
ReportsController.cs
public class ReportsController : Controller
{
public ActionResult Search(SearchViewModel model)
{
if (!ModelState.IsValid)
return View(model);
// do search magic here
return View(model)
}
}
Search.cshtml
#model ISFinReports.Models.SearchViewModel
#{
ViewBag.Title = "List";
Layout = "~/Views/_masterLayout.cshtml";
}
<link href="~/CSS/Search.css" rel="stylesheet" />
<script src="~/Scripts/Search.js"></script>
#using (Html.BeginForm("Search", "Reports", FormMethod.Get))
{
<div id="divSearchBar">
// add #Html.DropDownListFor, #Html.TextBoxFor and submit button here
</div>
<div id="divReportsTable">
<table id="tblReports">
#if (Model.Reports != null)
{
foreach (var r in Model.Reports)
{
// add tr, td of all reports in report list
}
}
</table>
</div>
<div style="text-align:center">
#for (int i = 0; i < Model.PageCount; i++)
{
#Html.ActionLink(i.ToString(), "Search", "Reports", new { CurrentPage = i });
// or
// <input type="submit" value="#i" onClick="meybe something like this?" />
}
Current Page #Html.EditorFor(q => q.CurrentPage), of total #Model.PageCount pages
</div>
}
I know that I can simply type twice all the data I need to flow between controller and view, once in model and once as Search action parameters, but that's extactly what I'm trying not to do. Currently I have a textbox for editing the current page, and it works, because it's created via #Html.EditorFor, but I'd like to have multiple buttons for each page.
I could maybe create a hidden field in that form, and create a javascript function that'll find that hidden field by id, and change it's value, and then call whatever the submit button onClick function is. BUT, is there a better/shorter/more-MVC way to implement that?
One of the overloads for Html.RenderPartial allows you to pass in a model. How can you make use of that from _Layout.cshtml?
I have a model prepared with everything I need. I just can't see how to make it accessible to the Layout.
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
<nav>
#{ Html.RenderPartial("pMenu", menu); }
</nav>
...
pMenu.cshtml
The partial view for the menu. Hopefully this makes it clear that the menu is dynamic and really does need a model passed to it.
#model MyApplication.Menu
#foreach (KeyValuePair<string, MyApplication.MenuGroup> group in Model.group)
{
if (group.Key != "default")
{
<div>#group.Key.ToString()</div>
}
<ul>
#foreach (MyApplication.MenuItem item in group.Value.items.Values)
{
<li>
#if (item.isCurrent)
{
<span class="#item.Icon">#item.LinkText</span>
}
else
{
#Html.ActionLink(item.LinkText, item.Action, item.Controller, item.RouteValues, new { #class = #item.Icon })
}
#if (null != item.subItems)
{
<ul class="tree">
#foreach (MyApplication.SubItem subitem in item.subItems)
{
<li>
#if (subitem.isCurrent)
{
<span>#subitem.LinkText</span>
}
else
{
#Html.ActionLink(subitem.LinkText, subitem.Action, subitem.Controller, subitem.RouteValues, null)
}
</li>
}
</ul>
}
</li>
}
</ul>
}
Where is the menu instantiated?
public class MainController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
menu = new Menu(requestContext.RouteData.Values);
Background information
This is an intranet application. It does not have the typical hard-coded menu options of "Home", "About", "Contact". Most of the menu is created from user-maintained database records. The menu is individualised to the user. No two users will have the same menu items. Eg: A manager gets a menu item for each of their staff.
The menu model also handles other factors that make the menu "dynamic" such as:
identifying whether the requested page matches a given menu item (by route data) (for styling)
adding extra menu items based on roles
sometimes adding sub-menus for the current context
This seems similar to #Render partial with a model in Layout View but I think that question went off the rails by referring to session.
Disclaimer: I'm an experienced programmer but relatively new to C# and asp.NET MVC.
ViewData to the rescue.
_Layout.cshtml
#{ Html.RenderPartial("pMenu", ViewData["menu"]); }
MainController
menu = new Menu(requestContext.RouteData.Values);
ViewData["menu"] = menu;
Modifying menu after this point still works. I'm not sure why, but I'll take it.
See also Best way to do global viewdata in an area of my ASP.NET MVC site?
I think you want to render a menu. from my view you should create a helper method for this purpose. If you want to go through this technique and if you are new to create your own tag then following this basic tutorial to get some undestanding : http://www.codeproject.com/Articles/787320/An-Absolute-Beginners-Tutorial-on-HTML-Helpers-and
You could always include a base index view that contains generic things then reference your layout in the page. You somewhat inherit the view and send in model data.
#model Model.MyIndexModel
#{Layout = "~/Views/Shared/Layouts/_SinglePageLayout.cshtml";}
I create a small form and give the link to my customer so he include the view in one IFRAME in his page and show ok.
When user submit the IFRAME form instead of redraw inside the IFRAME take the whole page.
...
ViewBag.result = "Form send correctly";
return View();
What should I use instead return View(); ?
I think the problem is not on the controller. It is on your View. You could try set a name for the elements iframe and target your form to post on this element, for sample:
<iframe src="#Url.Action("ActionName", "ControllerName")" name="foo"></iframe>
and in your View inside the iFrame
#using(Html.BeginForm("Action", "Controller", FormMethod.Post, new { target = "foo" })
{
..
}
I guess your problem is, It shows the layout which you do not want to be shown in the iFrame.
You can disable the layout in the razor view
#{
Layout = null;
}
If you remove the layout from the page, you will loose all the JS and CSS you loaded via the Layout file. In that case, you may use a minimalistic Layout which still has reference to your required CSS/JS files.
#{
Layout = "~/Views/Shared/MyMiniLayout.cshtml;
}
You can customize the MyMiniLayout the way you want.
You may show another view once the form submit is completed instead of showing the same view.
[HttpPost]
public ActionResult Register(string name)
{
// to do :Do something with posted data
return RedirectToAction("FormSubmitted");
}
public ActionResult FormSubmitted()
{
return View();
}
You can put whatever markup you want to show to user in the FormSubmitted view.
#{
Layout = null;
}
<h2>Submitted successfully</h2>
I've got an asp.net MVC website that consists of a topbar and a main area.
Via a js function, I want to be able to retrieve new data from my Controller and display these data in the main area of my website, but without re-rendering the topbar area.
How do I do this?
Here is what I got:
I put the topbar and all related scripts in the _layout.cshtml, scripts related to the mainview go to Display.cshtml and the data itself which I want to display go inside Partial_ChartView.cshtml
The partial view that should display my chart data is loaded inside Display.cshtml like this:
#model MobileReports.Models.ReportViewModel
#{
ViewBag.Title = "Display";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{Html.RenderPartial("Partial_ChartView");}
The partial view Partial:ChartView.cshtml looks like this:
#model MobileReports.Models.ReportViewModel
<div id="chartContainer">#Model.Chart</div>
The corresponding controller contains this code:
public ActionResult Display(Guid? id)
{
ReportViewModel viewModel = new ReportViewModel();
Guid validId = (Guid)id;
viewModel.Chart = GetChart(guid);
viewModel.ChartData = GetData(guid);
return PartialView(viewModel);
}
When I open the page at ../Report/Display , the page seems to get rendered correctly.
Now I want to add a script that calls Display(id) with a certain value. Then I want to re-render only the main area (inside div #chartContainer) to display the new data which should now be in the model.
How do I do this?
Create a new method that returns a partial view containing only the data you need
public ActionResult Chart(GUID id)
{
.....
return PartialView(someModel);
}
then use jquery .load to replace the contents of your div
$('#chartContainer').load('#Url.Action("Chart", "Report")', { id: YourGUIDValue });
I want to return a for a certain controller a blank page.
By blank, i mean blank!. with no Site.Master contents.
How?
Thanks
This will return an empty view
public ActionResult MyAction()
{
return new EmptyResult();
}
if you want no html or content, just return null from your action method.
Are you wanting to return a page that does not inherit from your master page? If so then in your view page, do the below
#{
Layout = null;
}