MVC5 Html.RenderAction with different controller - asp.net-mvc

I am starting with MVC5 and created first project from MVC5 Getting Started.
Now trying with Partial Rendering and added a method in MoviesController as below
[ChildActionOnly]
public ActionResult PriceRange()
{
var maxprice = db.Movies.Max(m => m.Price);
var minprice = db.Movies.Min(m => m.Price);
ViewBag.MaxPrice = maxprice;
ViewBag.MinPrice = minprice;
return PartialView();
}
It sets Min and Max price from Movies collection into ViewBag that are later displayed at view. I am trying to render it on different views.
First i tried to render it at Views/Movies/Index.cshtml as below
#{Html.RenderAction("PriceRange");}
It works well there and results displayed correctly because it is using MoviesController, the same class where method PriceRange defined.
Then i tried to render it at Views/Hello/Index.cshtml (this view is using HelloWorldController) with following code (first passing Action name then Controller name)
#{Html.RenderAction("PriceRange", "MoviesController");}
Here it is giving run-time error
The controller for path '/HelloWorld/Index' was not found or does not implement IController.
Here is complete code from Views/Hello/Index.cshtml
#{
ViewBag.Title = "Movie List";
}
<h2>My Movie List</h2>
<p>Hello from our view template</p>
#{Html.RenderAction("PriceRange", "MoviesController");}
I found few examples through Google, they are calling RenderAction helper the same way, first passing Action name then Controller name.
I couldn't understand what the wrong i am doing here.
Can someone point out?

It might be that you're adding the "Controller" postfix to the controller name which isn't required.
Try:
#{Html.RenderAction("PriceRange", "Movies");}

The controller name needs to be "Movies" and not "MoviesController". Because now I believe it is looking for a controller called "MoviesControllerController".

Related

Get title of page that calls render action

I'm using Render action to inject some tabs into a calling view. I want to be able to get the Title of the view executing the RenderAction method however in the partial view I can't seem to access the viewbag or viewdata. It was my understanding that a partial view gets a copy of the parents viewbag / viewdata dictionary.
I've tried ViewBag.Title and ViewData["title"] but nothing gets returned. Any ideas?
When you use RenderAction, the model used by that action is independent from the one that is in use when you call RenderAction. The same goes for ViewBag and ViewData. If your action called by RenderAction contains no logic, you could change it to RenderPartial to share the model between parent and child actions.
(Posted answer on behalf of the question author in order to move it from the question post).
I found out that if you create a model you can pass that model into the render actions method:
public class ViewInfo{
public string Title { get; set; }
}
then call the renderaction method:
#{ Html.RenderAction("RenderTabs", "Tab", new {Title = ViewBag.Title});}

Can't Render an MVC View without a Model

I'm having issues rendering a view without a model associated to it. I created a separate MVC project (the out of the box one in VS2013), created a view without a model and the view rendered with no problem. Now for this project, I created a view with its associated controller and ActionResult method in that controller but unless I have a model associated in this view and pass one in it, I get an error "Object reference not set to an instance of an object." I didn't think a view had to have a model associated to it and passed in. Here is what I have so far.
The view is called MainAddress and I'm not associating a model with it. All it has in it is the ViewBag.Title and a paragraph tag with "Test".
Here is the code in the controller:
public ActionResult MainAddress()
{
return View();
}
Here is the view code:
#{
ViewBag.Title = "Main Address";
}
<h1>Test</h1>
Is there a setting that is set somewhere making a model required or am I just doing something wrong?

ASP MVC 4 - binding and passing data from view to controller in repeating controls

Being new to ASP MVC, I met the following problem.
I have a list of "repeating" controls on my page, which are presented by the following Razor code:
#model BankBLL.Interfaces.ISecureFolder
...(some irrelevant code here)
<header><h3 >Commitee list</h3></header>
#foreach (var commitee in Model.Commitees)
{
<a href="#Url.Action("CommiteePage", "SecureFolder", commitee)">
<div class="commiteeButtonImageContainer">#commitee.Name</div>
<img src="~/Images/CommiteeButtonImage.png"/>
</a>
}
Model.Commitees here is a List of ICommitee objects, that means that I am trying to "bind" each Url.Action to a corresponding ICommitee commitee object.
However, when it comes to my controller action:
public ActionResult CommiteePage(ICommitee commitee)
{
return View("CommiteePage", commitee);
}
looks like I am making it a wrong way, because application returns "Cannot create an instance of an interface." error, that means that application is unable to retreive required commitee object when the action link is clicked.
Is there a way to bind each row "item datacontext" (ICommitee object in this case) to correspoding Url.Action?
Unfortunately could not post it earlier due to reputation regulations.
Finally resolved this issue due to good explanation at:
HTML.ActionLink method
When you try to pass an argument from Url.Action or Html.ActionLink - you have to specify explicitly the final "null" argument responsible for html arguments.
In my case the following code works correctly:
slightly changed controller action (now receives just name instead of commitee object itself)
public ActionResult CommiteePage(string commiteeName)
{
return View("CommiteePage", SecureFolder.Commitees.First(o=>o.Name == commiteeName));
}
and changed syntax for html calling this action:
#foreach (var commitee in Model.Commitees)
{
<a href="#Url.Action("CommiteePage", "SecureFolder", new { commiteeName=commitee.Name }, null)">
<div class="commiteeButtonImageContainer">#commitee.Name</div>
<img src="~/Images/CommiteeButtonImage.png"/>
</a>
}
Now view correctly passes the name of selected commitee to controller so that I can redirect to corresponding commitee view.
Thank you all for helping to resolve this issue!
The main problem is that the default model binder cannot create an instance of an interface. Try to be more specific, i.e. public ActionResult CommiteePage(ImplementedCommiteeType commitee). You can also create a CommiteeViewModel: ICommitee class in which you can transport your structures (in Controllers and Views only).
Or you can create your own model binder which knows what to implement. This is slightly more complicated.

ASP.Net MVC render view from another controller to string

I am struggling for hours to render a view from another controller to a string.
I use that to generate email templates. For this I created a controller called EmailController that has a view ConfirmationEmail.cshtml
I want to render that view in Home.Index action for example. The reason for this is organisation because I want to have the email views in ~/View/Email/... and EmailController will be used just for rendering them. Also ~/View/Shared/Email/... will be ok if you have another suggestion.
Do you suggest another approach?
I saw this thread ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action but I cannot make it work.
I need something like:
public ActionResult Index()
{
EmailController emailController = new EmailController();
ControllerContext context = new ControllerContext(this.ControllerContext.RequestContext, emailController);
EmailController.RenderPartialViewToString(emailController, "ConfirmationEmail", new EmailModel());
}
This does not work :( and the viewResult object in RenderPartialViewToString method is null.
Do you have a solution for this?
Did you check out MvcMailer project?
https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
Why not use FluentEmail? It takes a few seconds to setup using Nuget, and you get all the goodness of Razor templates, with a simple to use email tool.
EmailController.RenderPartialViewToString you passed in emailController instead of context
Modify that line to something like:
EmailController.RenderPartialViewToString(context, "ConfirmationEmail", new EmailModel())

Correct way to write an ASP.NET MVC action returning a PartialViewResult

I have written an Action method for an ASP.NET MVC controller, which is being used to provide a model to a usercontrol.
public class ProductsController : Controller
{
public PartialViewResult ProductSummary()
{
ViewData.Model = new ProductSummaryModel("42"); // dummy data for now
return new PartialViewResult()
{
ViewData = ViewData
};
}
}
I am using the 'futures' Microsoft.Web.Mvc dll and rendering the control in my main view like this :
<% Html.RenderAction<ProductsController>(x => x.ProductSummary()); %>
What I have here appears to work just fine, but i attempted to google new PartialResult() to see if what I was doing was following the correct patterns.
Currently this search only comes up with 4 results!
So I figured I'm doing somethin wrong here in my controller. Whats the correct way to create an action method that returns a partial view? And what (if anything) is wrong or bad about what I'm doing.
I usually just use:
return PartialView("MyView", myModel);
But this just returns a new PartialViewResult("MyView", myModel) so it is potatoes/potatoes.

Resources