Multiple calls to a controller on the same page - c#

I have a Model that loads the Sidebar for my webpage, along with a Model that loads the main content. The content Model will be different for each page whilst the Sidebar model will remain constant. The content Model will change by the user clicking links:
~/Home/About
~/Home/Contact
What I ideally want to to put a line of code in _Layout.cshtml that loads a Controller that returns a PartialView displaying the Sidebar Model. So we might have:
<div id="sidebar">
#Html.Render("~/SidebarController/GetSidebar");
</div>
<div id="content">
#RenderBody()
</div>
But I know this won't work. How do I achieve this?

What I would do is to use #Html.Action("GetSidebar") in the _Layout.cshtml file, then you can have an action in your controller
public ActionResult GetSidebar()
{
//do stuff, populate menu items from database? etc
// Pass the data to the partial view
return PartialView("_Sidebar");
}
You would need this in each of your controllers unless you put this in a base controller, which you can then inherit on all your other controllers and add [ChildActionOnly] to the top of your action so that it can not be called directly.

I do the same thing you are trying to do. I use:
#Html.Action("GetSidebar", "SidebarController")
to draw my side bar and it works fine. I use ajax calls when changing views though so as to save on loading the sidebar over and over again and I have the ajax target the "content" div replacing its content with the partial view that represents each page.

Related

ASP.NET Core MVC - Partial view only renders on one page

I have a partial view for ViewBag.count, which is defined in the ShoppingCartController. The problem is that the ViewBag will only show when you are on the ShoppingCart View. I want the ViewBag to be seen on all views. How do I fix this? I am currently rendering the partial like this:
#Html.Partial("_ShoppingCart", new List<bytme.Models.ShoppingCartModel>())
The partial view called _ShoppingCart:
<span class="badge">#ViewBag.count</span>
You should create a seperate action method which returns HTML markup needed to render the cart section of your page and include that in all your view using Html.Action method.
You may also decorate this action method with ChildActionOnly attribute so that users's cannot directly access this action method by requesting the url /ShoppingCart/Cart.
[ChildActionOnly]
public ActionResult Cart()
{
ViewBag.ItemCount = 2; // replace hard coded value with your actual value
return PartialView();
}
and in your partial view (~/Views/Shared/Cart.cshtml), you may write the HTML code which is needed for the cart segment of the page.
<span class="mycart">
Total items in cart #ViewBag.ItemCount
</span>
Here we are using ViewBag to pass the item count numeric value from the action method to it's partial view. But you may use a view model and use the strongly typed view approach to pass data from your action method to the partial view (this is my preferred approach).
Now in other views/layout file where you want to render the cart HTML, you can call the Html.Action method
<div>
#Html.Action("Cart","ShoppingCart")
</div>
<h1>Welcome to my site</h1>
When razor execute your view, it will see this Html.Action method and that will be executed and the output of that (the HTML markup generated fro the action method), will be included in the final output generated for the current view.
I am using the PartialView method, so that it will not try to execute the Layout code. (People make this mistake and gets an infinite calls to the Cart action method.
For Asp.Net Core projects
If you want to do the same thing in asp.net core projects, you may use View components to achieve the same results.
Create a view component to render the cart.
public class CartViewComponent : ViewComponent
{
public IViewComponentResult Invoke(string name)
{
var totalItemCount = 3;
return View(totalItemCount);
}
}
Create a razor view for this view component with the name Default.cshtml inside ~/Views/Shared/Components/Cart directory and you can have your razor code/HTML markup inside that to render the desired HTML. In this example, I am using a strongly typed approach where my view is stongly typed to int type and I am passing an int value from the the Invoke method when calling the View method.
#model int
<span>
Total items : #Model
</span>
Now you can invoke this view component in other views/ layout file by calling the Component.InvokeAsync method.
<div>
#await Component.InvokeAsync("Cart")
</div>
<h1>Welcome to my site</h1>

Determine what View is going to be rendered in #RenderBody()

In _Layout.cshtml is it possible to determine what View is going to be rendered in #RenderBody() ?
You can get the View (i.e. Index.cshtml) through ((RazorView)ViewContext.View).ViewPath
Example for your needs:
<script type="text/javascript" src="~/Content/Scripts/#(Path.GetFileNameWithoutExtension(Server.MapPath(((RazorView)ViewContext.View).ViewPath))).js"></script>
If you need your actual View (i.e. _Layout.cshtml), you can use VirtualPath instead.
Old answer
Reading your comments, you want to add a
<script ...>...</script>
depending on the view but outside of #RenderBody()?
Then put
#RenderSection("Scripts", required:false)
and in your view define the section like
#section Scripts {
<script ...>...</script>
}
So you don't need to maintain your _Layout.cshtml since every View defines their own scripts.
Here is an easy explanation: http://weblogs.asp.net/scottgu/asp-net-mvc-3-layouts-and-sections-with-razor
What you can do is check Html.ViewContext.RouteData.Values. That's a dictionary with controller, action, and id (as necessary).
Read this article and it will solve your problem.
Edit
RenderBody
What is RenderBody?
In layout pages, renders the portion of a content page that is not
within a named section. [MSDN]
How RenderBody works (graphical presentation)?
The #RenderBody() renders the view controlled by the controller. so if your controller is like this.
public class HomeController : Controller
{
public ActionResult Index() // Renders File /Views/Home/Index.cshtml
{
return View();
}
}
Then the public ActionResult Index() Index.cshtml will be the view it will render located int the /Views/Home folder.
You can add to the Index.cshtml or _Layout.cshtml view to render other Views or partialViews By adding #Html.Partial("_MyView") as shown below.
#Html.Partial("_LayoutHeaderHeader")
#Html.Partial("_LayoutHeaderNavbar")
Sometimes it is easy to setup a few layout pages to call from different Views.
If you want to call scripts to you View you should always create a _PartialView and place your scripts in the partial view and call that View at the bottom of your View like this #Html.Partial("_MyView") and the scripts will set properly.
Here is a good tutorial. http://www.codeproject.com/Articles/698246/ASP-NET-MVC-Special-Views-Partial-View-and-Layout
If you derive all your models from a base model then you could add a property to you base model that returns the controller name, which you can get using
this.RouteData.Values["controller"].ToString();
It would be even better if you had a BaseController class because you could put this in the constructor and never have to touch it again.
Since you would be returning a descendant of the base Model to your index page which has the controller name, now you could use some scheme base on #Model.ControllerName. If your controller services multiple views the property could be updated to indicate a certain view name.
I don't think you can get the name of a Partial inside the index unless you use jquery and by that point the page resources have already been loaded.
Edit: One other trick would be to create your own version of #Html.Partial() HtmlHelper class. So you have #Html.MyPartial("ViewName") and inside that method call the internal function that generates Html.Partial and then inject your dependencies.
EDIT: I just read your comments about the issue and think that the better way is using the code snipplet provided by #Matt in another answer.
You can use the #section razor statement inside your view to inform wich script should be loaded.
Layout template placeholder
#RenderSection("scripts", required: false)
View Code
#section scripts {
<script src="~/Scripts/custom-imgedit.js"></script>
}
The example above inform that the custom-imgedit.js will be loaded in the render section placeholder. Note: You can even use bundles like #Scripts.Render("~/bundles/myCustomScripts")

Show one view as a part in another view in mvc5

I have 3 different views and their respective controllers and action methods. On respective button clicks I am showing each view so far.
Now the client request is a new view, which contains the 1st view as half of the page and the remaining two views as the tabbed views. By default one of the tabbed view has to be loaded in next half of the page, the other view loads only on demand means on the respective tab click.
Note: Each view is from a service call.
Please give me some examples or references to work with. I am hoping for minimal changes in my code
Why don't you create it as partial view and you can load it in Tabbed div or any other div. This way you can have as many views you want on a page. Aslo you can load a view later on some event of that page. check this stack.
From what you've described above and the comments you made under one and free's post, it seems that you want to have a main page with several partial views rendered both inside and outside of a tabbed panel. Also, after changing the layout a bit you're having trouble resolving the models for (some of) those partial views.
If you are passing "coverageModel" to the main view, but the partial views required different models from different controllers, you should consider using something like the following (this is an example from Bootstrap, but may be applicable to your case):
<div class="tab-content">
<div id="tab1" class="tab-pane active">
#{ Html.RenderAction("Action", "Controller1");}
</div>
<div id="tab2" class="tab-pane">
#{ Html.RenderAction("Action", "Controller2");}
</div>
</div>
Again, your tab layout may be quite different from the above example, but the important thing is that RenderAction will be able to render a partial with a different model.

Passing a model with a Partial View

I want to show a view on some of my forms, which shows a list of alerts, read from a database table. I think I need to use a partial view - but haven't used one.
So far, I created a partial view in my shared views folder called "_Alerts.cshtml".
In that file, at the moment, I simply have:
#{
Layout = null;
}
This is a shared view.
This is just me trying to display something.
And then, on my existing page, on which I want to display the alerts, I have this section of code:
#if (User.Identity.IsAuthenticated)
{
<div class="row">
#Html.Partial("~/Views/Shared/_Alerts.cshtml", null)
</div>
}
This works. However, my understanding is not right. At the moment, I pass no model to it. Is there no controller for the partial view? At the moment, I need to create a controller method - somewhere - that gets me a list of alerts from my data service, and then I want to format that and present it in the partial view. But I am unsure where the controller methods go. If this view is called from 8 different screens, would the 8 controllers for these screens have a call to get my alerts, and format them?
Seems like a lot of duplication.
They need not be duplication.
You can define the action you want inside a controller and call #Html.Action instead of #Html.Partial
Inside you action you can return a partial view.
public class AlertsController : Controller
{
public ActionResult Show()
{
var model = GetModel();//decide where this will come from.
return PartialView("~/Views/Shared/_Alerts.cshtml",model);
}
}
In your layout view or wherever you need to use it. you can simply call it as below.
#Html.Action("Show","Alerts")
If you have all the data you need to pass into the partial, then you can use the #Html.Partial and pass in the model.
If on the other hand, you want the view you are embedding to get the data itself, then you would use Html.RenderAction

Best way to display a JQuery Dialog with ASP.NET MVC data bound View Model

Imagine a simple page with a list of users. Selecting a user displays a JQuery modal dialog with various details that can be edited. Something like:
#model IEnumerable<UserRole>
#if (Model.Any())
{
foreach (var user in Model.Users)
{
Details
}
}
I'll have more specific examples through the post but what I'm looking for is a general 'experienced' opinion on what's the best way to load and display a Model bound Partial View as a JQuery dialog box.
I know how to do it code-wise but I think there must be a better way. I believe the common known ways to do it are not very efficient.
My rule and what I would like is for all code associated to a partial view popup to be kept in that partial view. I would like my popup to be structured something like the following UserDetails partial view:
#model User
<script src="#Url.Content("~/Scripts/UserScripts.js")" type="text/javascript"></script>
<div id="placeholder">
...The modal dialog content...
</div>
This way when another developer gets to look at it one will easily be able to piece it all together.
So as far as I know there are two ways to display a partial view as a Dialog and I have a problem with both of them:
1) Use the Partial view structure I displayed above, pre-load the div dialog from the master page by using #Html.Partial("UserDetails", new User) and then, when I need the dialog to be displayed populated with user data execute an Ajax call to an ActionMethod that will re-populate the partial view's model with needed data and re-render it with JQuery .html() method.
Once the partial view/dialog is loaded with data I simply display it with JQuery .dialog('open')
Great, this works but there are a few problems with this logic:
a) I'm loading the same partial view twice ( first blank , second loaded with data )
b) Content of the Placeholder DIV flashes on the screen when the master page is being loaded. Setting DIV to display:none won't work here before when .html() method triggers it will load the partial view with that display:none tag in it and the popup will be presented as a blank window.
c) When the page is requested, if large, it takes some time for the page to show
2) Instead of having in the partial View I can place a blank <div id="placeholder"></div> on the master page and then load the partial view content into that div with ajax or as I'm doing it now with JQuery :
var url = "/MyController/MyAction/" + Id;
$("#palceholder").load(url).dialog('open');
Again, it works but there are a few big problems I see with this way:
a) It breaks my "keeping it all together rule". When looking at , without some searching around another developer will have no idea what partial view will be loaded in this Div.
b) All Javascripts for the partial view popup will now need to be referenced in the master page, instead of a the partial view itself.
c) When the page is requested, if large, it takes some time for the page to show
The bottom line question is what do you think is the best way to display the model-bound populated partial view as a Modal Dialog while keeping the code organized ?
My perfect scenario would be to pre-load all partial view fields and then, when the request is made for the dialog to show populated with Data somehow a model bind pre-loaded partial view to the new JSon set of data, without loading/re-loading all partial view fields.
Is there a way ?
P.S. One of the things I tried is to pre-load my partial view fields with #Html.Partial("UserDetails", new User) and then use JQuery .replaceWith() method to replace Div contents but I couldn't get it to work unfortunately.
Any thoughts are appreciated. No ideas as are bad ideas.
Thanks.
Nothing wrong with having part of your code load in partial, and then just updating the partial container with a return from action.
<div id="ParitalContainer">
#Html.Partial("_PartialView", Model.PartialModel)
</div>
Or, you can consider a scenario to work with JSON data. Namely, have all your data loaded async by calling a $.ajax or $.getJSON. Your action result would return JsonResult and then you can just update the elements you want.
Furthermore, you could look into using Knockout.js if you want more robust solution. This is what I would do if I wanted "keeping it all together" approach.

Categories