MVC 3 中 RenderAction 的问题
我想使用 MVC 和 renderpartial 来生成菜单,但无法让它工作,从我读到的内容看来 RenderAction 可能更合适。我仍然没有让它发挥作用。
我打算做的是创建一个控制器,从数据库中选择某些文章作为类别(这被放入 HomeController 中):
public ActionResult MenuController()
{
var movies = from m in db.Art
where m.ArtikelNr.StartsWith("Webcat")
select m;
return View(movies);
}
然后将该信息发送到视图:
@model IEnumerable<xxxx.Models.Art>
@{
Layout = null;
}
<ul>
@foreach (var item in Model)
{
<li>@Html.DisplayFor(modelItem => item.Benämning_10)</li>
}
当我只是将其作为普通控制器和视图运行时,它会起作用,它会返回我想要的列表。但是,如果我想从 _layout.cshtml 调用它(因为这个菜单应该出现在每个页面上),如下所示:
<div id="sidebar">@Html.RenderAction(MenuController)</div>
然后它会生成以下错误:
CS0103: The name 'MenuController' does not exist in the current context
What is the right way of Calling an action/view/whatever from the _layout.cshtml file ?
I wanted use MVC and renderpartial to generate a menu but but could not get it to work, and from what I read it seemed maybe RenderAction would be more suitable. Still I have not gotten it to work.
What I intended to do was create a controller that selects certain articles from a database that will act as categories (this is put into HomeController):
public ActionResult MenuController()
{
var movies = from m in db.Art
where m.ArtikelNr.StartsWith("Webcat")
select m;
return View(movies);
}
And then send that information to a view:
@model IEnumerable<xxxx.Models.Art>
@{
Layout = null;
}
<ul>
@foreach (var item in Model)
{
<li>@Html.DisplayFor(modelItem => item.Benämning_10)</li>
}
This works when I just run it as a normal controller and view, it returns a list of what I want. But if I want to call it from _layout.cshtml (because this menu should appear on every page) like this:
<div id="sidebar">@Html.RenderAction(MenuController)</div>
Then it generates the following error:
CS0103: The name 'MenuController' does not exist in the current context
What is the proper way of calling an action/view/whatever from the _layout.cshtml file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该致电
并确保您的 Global.asax 中有一个工作规则
正如另一个答案中所建议的那样,使用效果会更好
我还建议您使用 ChildActionOnlyAttribute 以确保此操作永远不会被称为标准操作。
所以类似这样的事情:
You should call
and be sure that you have a working rule in your Global.asax
As suggested in another answer would be better to use
I also suggest you to use the ChildActionOnlyAttribute to be sure that this action will never be called as a standard action.
So something like that:
或者
or
只是
@Html.RenderAction("MenuController")
您忘记了字符串参数周围的引号
Simply
@Html.RenderAction("MenuController")
You've forgotten quotes around your string parameter
将您的操作名称括起来:) 返回部分视图也可能是一个好习惯:
Quotes around your action name :) It might also be good practice to return a partial view: