partial view not displaying but its viewmodel works on parent - c#

In the cshtml code header I've instantiated a viewmodel with some data. I can bind to and display data from that viewmodel variable in the parent page. However, when I pass the viewmodel variable into a child partial view, nothing displays on the page.
#{
Html.Partial("DailyReport", #DailyReportViewModel);
}
Any idea why the child partial view would not be displaying on the page or how to debug this issue?

Because you are calling the Partial method which return an MvcHtmlString, but you are not using the return value of the method.
You can do this instead
#Html.Partial("DailyReport", #DailyReportViewModel);
Razor will now render the return value from the DailyReport method.
Or you can use the RenderPartial method which render the result.
#{
Html.RenderPartial("DailyReport", DailyReportViewModel);
}
Assuming DailyReportViewModel is an object of type T to which your partial view is strongly typed to.

Put # at the front and remove the # from DailyReportViewModel and it should work.
#Html.Partial("DailyReport", DailyReportViewModel);

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>

Sending Temporary data to multiple partial views from view MVC

I'm wondering if there is a good way to do this. I'm currently trying to send some temporary data to multiple partial views being called from the same view page in my MVC application.
I'm currently attempting to do this with TempData but I can see my understanding is limited as it is only going through for one partial request. What method do I need to use to filter out to all of my partials?
Main View Page:
#{
ViewBag.Title = "Main View Page";
TempData["ReturnUrl"] = Request.Url.OriginalString.ToString();
}
#Html.Partial("_StatusTable1")
#Html.Partial("_StatusTable2")
#Html.Partial("_StatusTable3")
#Html.Partial("_StatusTable4")
#Html.Partial("_StatusTable5")
Partial View Example:
#{
var temp = TempData["ReturnUrl"]; // temp is null on all partials except the first
}
// Partial View Code ...
Thanks in advance.
In your main view page call the partiel views like that
#Html.Partial("_SomePartial", TempData["ReturnUrl"])
I think that even this would work.
#Html.Partial("_SomePartial", TempData)
Get the value from TempData like this. ReturnUrl Value will retained across all the Partial Views
#{
var temp = TempData.Peek("ReturnUrl");
}
// Partial View Code

Returning Partial View ASP.NET MVC

Hi I have a partial view setup for handling error messages, but when it's returned it returns a full webpage with just the text No Results Found.
I would expect the Partial View to return inline on my main Index page? As in my Index page I have the code #Html.Partial("_ErrorMessage").
Below is how I'm handling this in my HomeController
else
{
ViewBag.Error = "No results found!";
return PartialView("ErrorMessage");
}
}
Partial view not necessary return html inline. Partial view can return html inline if you call by client script, using jquery, angular, etc.
This way did you make. The return is a whole page.
Context is important here. If you are including the partial view in line in the HTML, you probably don't need to return the partial view in C-sharp unless you're using a fancy asynchronous call to load it.
The in-line partial view should display normally if you just show the view where it was included
I am not sure what the exactly error you are facing but you can try following solution, you have to set Layout as null after you will not facing the full page on your partial view.
#{
Layout = null;
}
If you are not using Layout=null it will call your _Layout page.
Hope it helps you.

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

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