How to Write Get Action for layout - c#

I have layout _PageLayout.
I want to pass some model to layout _PageLayout which can be generate from context that is available in session.
So i want to write Get Action for layout _PageLayout.

You can not pass a model to a layout page in the same way that you can pass a model to a view page.
In the layout page you could call a child action method to retrieve the content you require rather than passing a model to the layout.
For example:
In the _PageLayout.cshtml page you can include a call to the child action like so:
#Html.Action("MyChildActionName", "MyActionName")
And then you can define a child action in the appropriate controller as follows:
[ChildActionOnly]
public ViewResult MyChildActionName()
{
var viewModel = //define view model with the contents from your session value here
return View(viewModel); //This should return a view that will be rendered within the calling View 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>

Can I Display User Specific Data throughout the site without adding to each view model

I have a site (MVC5) with a partial that is a header. This header displays the users name, and a logo of the organisation that they represent.
Each page also has a ViewModel of page specific data.
Is there any way I can have this Partial rendered on each page from a common model / object behind the scenes, or do I need to add my 'userheader' viewmodel to the viewmodel on each page?
You can get your requirement done through ChildActionOnly, lets say -
[ChildActionOnly]
public ActionResult LoggedIn()
{
// create your User View Model and pass it to Login Partial View
return PartialView("_LoginPartial", user);
}
Now create a Partial View with a stringly typed model what you are returning from the controller action above.
And in your Layout you can get the partial view like shown below -
#Html.Action("LoggedIn", "ControllerName")
In this way there is no need for you to include the same models across different views.

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

how to pass data from one view to another

I want to pass object data from one view to another on click of button.
I am calling the action to load the second view via ajax.
In the controller action I am trying to pass object data to view. But the view is not rendered.
How can I achieve the scenario of passing data from one view and populating it to the controls of other view?
I want to pass object data from one view to another on click of button
When in any Action or ActionResult you have
return RedirectToAction("controllerName","viewname","parameters")
so the Action Method instead of returning a view, this will redirect to another view Action method and that view will be rendered.
You need to send the data from one view to another in form of query string or post parameters to an action.
Ex:
[HttpPost]
public ActionResult PassData(string dataFromView1)
{
return View("View2", dataFromView1);
}
Note: Here i used a single string data in a parameter. If your View1 has more data/complex data structure, better to use ViewModel class and pass that to your intermediate controller.
I want to pass object data from one view to another on click of button
You need to pass View in HttpPost method. Look at this code.
[HttpPost]
public ActionResult YourActionName(Model model)
{
return View("AnotherActionName", model);
}
Or you can use RedirectToAction.

Getting the Controller and Action used to call

In a Partial View _MyView.cshtml I need to get the Controller name and the Action used to create the parent calling view.
So if /Equity/Sell was the Controller/Action used to call the view which rendered the partial view _MyView.cshtml , then I need the value /Equity/Sell.
I don't see an object that can do that though.
In the view use:
ViewContext.RouteData.GetRequiredString("controller");
ViewContext.RouteData.GetRequiredString("action");
For posterity in a child action it is like this:
ControllerContext.ParentActionViewContext.RouteData.Values["action"];
ControllerContext.ParentActionViewContext.RouteData.Values["controller"];

Categories