I have a index.cshtml page and index2.cshtml partial page in my file location of Views/Index/. I want to pass data from index.cshtml to index2.cshtml without using link, don't look in page.
For example:
index.cshtml:
#{
ViewBag.data = 1;
#Html.Partial("index2")
}
index2.cshtml(partial):
#ViewBag.data
Preview of index.cshtml is : 1
If you're using a partial to show index2 then your viewbag/viewdata should persist to the partial but if not you can pass the view data in the renderpartial method
#Html.RenderPartial("index2", Html.ViewData)
Related
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>
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
I created some views in visual studio by clicking right click=> add => view.
I select in the selection: "use a layout or master page".
Now I want to turn these views to partial views should I delete it and create new? or I can somehow turning it to partial view without deleting the views?
In Razor there is no much difference in View and partial view
Only difference is
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
If there is no layout specified they could be considered as partial views.
From your controller action you return PartialView(); instead of return View(); this layout will not be applied.
I am trying to dynamically render pages from database. The view looks like this
#model MyModel
#{
ViewBag.Title = Model.Title;
Layout = Layout = "~/Views/Shared/_PageInnerLayout.cshtml";
}
#MvcHtmlString.Create(Model.Content)
MyModel has just 3 properties; Id, Title and Content
If the Content has just HTML, the view renders just fine. But in some cases, I need to render partials too. So Content may contain code like
#{
Html.RenderPartial("_FooterPartial");
}
This does not work. Its being rendered literally, like shown in the image below
How do I fix this so that the page is rendered properly?
The problem is in the difference between Html.RenderPartial and Html.Partial helper methods. RenderPartial directly write the result to HttpContext.Response while Partial return it as a MvcHtmlString. You need to replace the RenderPartial with Partial and maybe the RenderAction with Action.
Edited:
You need to render the content if contains the razor view scripts. If so it means you are actually storing the views or partial views inside the database. You can create a new VirtualPathProvider to help loading the views from the database. For more information see ASP.NET MVC load the Razor views from database and ASP.NET MVC and virtual view
I tried doing this with VirtualPathProvider, but it didn't work.
Finally what I did was to write the Content from database into a temporary view and then render the view. It worked
public ActionResult DynamicPage(int id) {
var dynamicPage = new PagesContext().Pages.FirstOrDefault(s => s.Id == id);
string webroot = Server.MapPath("~").TrimEnd('\\');
string fileName = webroot + "\\Views\\\\Solutions\\Temp.cshtml";
System.IO.File.WriteAllText(fileName, dynamicPage.Content);
return View("Temp");
}
Here, the Content property of the dynamicPage containts HTML(including Razor code)
When would you use the attribute ChildActionOnly? What is a ChildAction and in what circumstance would you want restrict an action using this attribute?
The ChildActionOnly attribute ensures that an action method can be called only as a child method
from within a view. An action method doesn’t need to have this attribute to be used as a child action, but
we tend to use this attribute to prevent the action methods from being invoked as a result of a user
request.
Having defined an action method, we need to create what will be rendered when the action is
invoked. Child actions are typically associated with partial views, although this is not compulsory.
[ChildActionOnly] allowing restricted access via code in View
State Information implementation for specific page URL.
Example: Payment Page URL (paying only once)
razor syntax allows to call specific actions conditional
With [ChildActionOnly] attribute annotated, an action method can be called only as a child method from within a view. Here is an example for [ChildActionOnly]..
there are two action methods: Index() and MyDateTime() and corresponding Views: Index.cshtml and MyDateTime.cshtml.
this is HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "This is from Index()";
var model = DateTime.Now;
return View(model);
}
[ChildActionOnly]
public PartialViewResult MyDateTime()
{
ViewBag.Message = "This is from MyDateTime()";
var model = DateTime.Now;
return PartialView(model);
}
}
Here is the view for Index.cshtml.
#model DateTime
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<div>
This is the index view for Home : #Model.ToLongTimeString()
</div>
<div>
#Html.Action("MyDateTime") // Calling the partial view: MyDateTime().
</div>
<div>
#ViewBag.Message
</div>
Here is MyDateTime.cshtml partial view.
#model DateTime
<p>
This is the child action result: #Model.ToLongTimeString()
<br />
#ViewBag.Message
</p>
if you run the application and do this request http://localhost:57803/home/mydatetime
The result will be Server Error like so:
This means you can not directly call the partial view. but it can be called via Index() view as in the Index.cshtml
#Html.Action("MyDateTime") // Calling the partial view: MyDateTime().
If you remove [ChildActionOnly] and do the same request http://localhost:57803/home/mydatetime it allows you to get the mydatetime partial view result:
This is the child action result. 12:53:31 PM
This is from MyDateTime()
You would use it if you are using RenderAction in any of your views, usually to render a partial view.
The reason for marking it with [ChildActionOnly] is that you need the controller method to be public so you can call it with RenderAction but you don't want someone to be able to navigate to a URL (e.g. /Controller/SomeChildAction) and see the results of that action directly.
FYI, [ChildActionOnly] is not available in ASP.NET MVC Core.
see some info here
A little late to the party, but...
The other answers do a good job of explaining what effect the [ChildActionOnly] attribute has. However, in most examples, I kept asking myself why I'd create a new action method just to render a partial view, within another view, when you could simply render #Html.Partial("_MyParialView") directly in the view. It seemed like an unnecessary layer. However, as I investigated, I found that one benefit is that the child action can create a different model and pass that to the partial view. The model needed for the partial might not be available in the model of the view in which the partial view is being rendered. Instead of modifying the model structure to get the necessary objects/properties there just to render the partial view, you can call the child action and have the action method take care of creating the model needed for the partial view.
This can come in handy, for example, in _Layout.cshtml. If you have a few properties common to all pages, one way to accomplish this is use a base view model and have all other view models inherit from it. Then, the _Layout can use the base view model and the common properties. The downside (which is subjective) is that all view models must inherit from the base view model to guarantee that those common properties are always available. The alternative is to render #Html.Action in those common places. The action method would create a separate model needed for the partial view common to all pages, which would not impact the model for the "main" view. In this alternative, the _Layout page need not have a model. It follows that all other view models need not inherit from any base view model.
I'm sure there are other reasons to use the [ChildActionOnly] attribute, but this seems like a good one to me, so I thought I'd share.
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.TempValue = "Index Action called at HomeController";
return View();
}
[ChildActionOnly]
public ActionResult ChildAction(string param)
{
ViewBag.Message = "Child Action called. " + param;
return View();
}
}
The code is initially invoking an Index action that in turn returns two Index views and at the View level it calls the ChildAction named “ChildAction”.
#{
ViewBag.Title = "Index";
}
<h2>
Index
</h2>
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<ul>
<li>
#ViewBag.TempValue
</li>
<li>#ViewBag.OnExceptionError</li>
#*<li>#{Html.RenderAction("ChildAction", new { param = "first" });}</li>#**#
#Html.Action("ChildAction", "Home", new { param = "first" })
</ul>
</body>
</html>
Copy and paste the code to see the result .thanks