ChildActionOnly attribute not working [duplicate] - asp.net-mvc

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

Related

Partial View different model

I am trying to use a partial view that uses a different model than the one used in the main view. The partial view has
to show a list with the products recently added. But I am stuck on how and where to implement the logic for retrieving the data I need from the database.
Home/Index.cshtml:
#Html.Partial("~/Views/Shared/_LatestProducts.cshtml", new List<Website.Models.LatestProductsList>())
Shared/_LatestProducts.cshtml:
#model List<Website.Models.LatestProductsList>
#foreach (var item in Model)
{
<a href="#" title="img">
<img src="~/Content/images/latest-product-img.jpg" alt="" /><p>#item.ProductName</p>
</a>
}
And I have the following code that I am trying to use in order to get some products for tests and show them in the partial view:
public PartialViewResult _LatestProducts()
{
List<LatestProductsList> latestProd = (from p in db.Products
where p.ID < 5
select new LatestProductsList { ProductName = p.Title }).ToList();
return PartialView(latestProd);
}
I thought that I might use it in the HomeController, but that obviously doesn't work and I am not sure if partial views should have their own controller, if I can
just call it from another class. I am still wrapping my head around ASP MVC, so any help will be appreciate it.
Just call the action that renders the partial view in Index.cshtml.
#Html.Action("_LatestProducts", "Product")
Second parameter is the name of the controller that has the _LatestProducts method.
Just a reminder: Names with _ prefix is for partial views only, not action methods. You should rename it to LatestProducts.

MVC Razor call to #Html.Action() in VB.NET always calls the New() Sub, even if I'm explicitly passing the model to use.

I'm building a Model in my Controller that I want to pass through an ActionResult on a different Controller. So in the Controller I have:
Public Class IndexViewModel
Sub New()
Ribbon = New Ribbon.RibbonViewModel
etc...
End Sub
Property Ribbon As Ribbon.RibbonViewModel
End Class
And then in the Razor View I make a call to render it like so:
#ModelType ANA.Inbox.IndexViewModel
<div>
#Html.Action("Index", "Ribbon", Model.Ribbon)
</div>
which goes to the RibbonController, which looks like:
Function Index(Optional Model As RibbonViewModel = Nothing) As PartialViewResult
If (Model Is Nothing) Then
Model = New RibbonViewModel
End If
Return PartialView(Model)
End Function
Before I even hit that first If(), I'm hitting a call to RibbonViewModel's constructor to create a new one instead of using the one I'm passing. Any ideas?
If you are not doing anything complex in Action, it will be better to use Html.Partial method to render partial view without calling action method

Httppost different named view and action method

I have a view called "page.chtml" and I want to post from it to an action called "actionname"
[HttpPost]
public ActionResult actioname(...){...}
Is it possible?
Yes you can. In the action property of the form in page.cshtml simply specify actionname:
<form action="actioname">
you can use Html helper for creating a form with your desire submit action
#using (Html.BeginForm("actionName", "ControllerName", FormMethod.Post, new { id = "FormId", name = "FormName" }))
{
<div>//your page.cshtml inner html code goes here
}
If you want to post a form to a different action name, you can use the HTML helper for that. In Razor syntax it looks like this:
#using (Html.BeginForm("actioname"))
{
<!-- Form Fields -->
}
There are a few parameters you can use - the action is one, another is the controller in case you want to post to an ActionResult in a different controller than the one that handled the request for the page initially.
Yes You can use actioname in different controllers and post it:
in any view in any controller you can post:
#using (Html.BeginForm("actioname", "Controller", FormMethod.Post))
{
}

MVC get controller in helper class

I need to be able to get a controller name in my custom helper class.
I have the following:
Layout view which calls a controller: "HelperController", action: "Menu" like so:
#Html.Action("Menu", "Helper")
This calls ActionResult and generages an html:
#model List<MvcMenuItem>
#{
Layout = null;
}
#{
#Html.Menu(this.ViewContext).ClientId("navMain").AddRange(Model).Render()
}
This calls "public static class MvcMenuExtensions" and in there (in my Render() method) I need to be able to get the controller name I'm currently in, NOT the controller name that is calling MvcMenuExtensions
I've tried this:
string controller = this.ViewContext.RouteData.Values["controller"].ToString();
but this results in controller being "Helper" controller and not the current controller I'm in. Since this "ActionResult" is being called from anywhere on the page (it's in the layout).
Thanks
answered here: How to get current controller and action from inside Child action?
by juhan_h
ControllerContext.ParentActionViewContext.RouteData.Values["action"]
OR
ViewContext.ParentActionViewContext.RouteData.Values["action"]

Where to put controller-wide accessible objects

I would like give access to the (currently logged-in) user object to all controllers, and views, in my application. For example, I want to put the users name in my "sidebar" partial, but don't know how to access the user object since that is stored in an other controller. Thanks in advance.
You could use the Html.Action helper method. You could define a view model which will contain all the necessary information you would like to show about the currently logged in user (like his username for example) and then have a controller action which will use the User property of the controller to populate this view model and pass it to a corresponding partial view. Then inside your master page you would include this information using the Html.Action helper:
<div id="sidebar">
#Html.Action("Index", "Users")
</div>
which will invoke the Index action of the UsersController:
public class UsersController
{
public ActionResult Index()
{
UserViewModel model = ...
return PartialView(model);
}
}

Resources