Where to put controller-wide accessible objects - asp.net-mvc

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);
}
}

Related

MVC Moving from one Model View to Another Model View

I am trying to move from one Model's view to another Model's view. I have a Person model and a BurnProject model. From my Person's Index view I have a "Select" link in which I would like for it to go the BurnProject's Index view. I have tried a couple of things neither have worked.
public ActionResult BurnProject()
{
//return View("~/Views/BurnProject.cshtml");
return RedirectToAction("Index", BurnProject);
}
From my Person's Index view I have a "Select" link in which I would
like for it to go the BurnProject's Index view
Why not create a link which navigates to the index action method of BurnProjectsController ?
So in your Person's index view, you may use the Html.ActionLink helper method.
#model Person
<h1>This is persons index view<h1>
#Html.ActionLink("Select","Index","BurnProjects")
This will generate html markup for an anchor tag which has href attribute set to "BurnProjects/Index".
If you want to pass some data from the person's index view to your BurnProject index action, you can use another overload of Html.ActionLink
#model Person
#Html.ActionLink("Select","Index","BurnProjects",new {#id=Model.Id},null)
Assuming your Person entity has an Id property(which you want to pass the value for) and your BurnProjects index action accepts an id param
public ActionResult Index(int id)
{
// return something.
}

ChildActionOnly attribute not working [duplicate]

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

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

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"]

How to use JQuery Dialog to post sub-set of data on form and refresh parent in MVC?

I have a JQuery dialog which is rendered in a partial view within a main view.
I want the form to post the whole parent page back so it is refreshed on submitting the data. However, the model that I use is stored in a class off the main model class e.g. MainModel.Current
At the top of the dialog I have the link to the MainModel (#model...)
Then in the helpers use lambda like so: m => m.Current.Field
In the controller, the model being passed into the parameter of the function is null?
Is there any reason for this? How do I go about passing in a different model or a subset of the model and refresh the parent.
Its a nightmare in mvc.
Updated
In main view:
#model MyProject.ParentModel
...
Html.RenderAction("AddChildData");
In partial view:
#model MyProject.ParentModel
#Html.TextBoxFor(model => model.ChildData.Name)
#Html.ValidationMessageFor(model => model.ChildData.Name)
In controller:
[HttpPost]
public ActionResult AddItem(ParentModel parentModel)
{
myService.AddItem(parentModel.childData); <-- parentModel is null
return RedirectToAction("Index");
}
Turns out this was because I had a nested form and this was intercepting the model data of the parent form.

Resources