MVC:传递参数以查看? [英] MVC: pass parameter to view?
问题描述
MVC新手问题:
我要获取一个格式为go/{mainnav}/{subnav}
的URL,该URL已成功路由到GoController
类的方法:
I'm picking up a URL of the form go/{mainnav}/{subnav}
, which I've successfully routed to the GoController
class, method:
public ActionResult Index(string mainnav, string subnav) {
return View();
}
到目前为止,太好了.但是现在我希望视图根据mainnav或subnav的值返回不同的HTML.具体来说,我想在一个JavaScript块中加入以下行:
So far, so good. But now I want the view to return different HTML, depending on the values of mainnav or subnav. Specifically, inside a javascript block, I want to include the line:
myobj.mainnav = [value of mainnav parameter];
,并且,仅当subnav不为null或为空时:
myobj.subnav = [value of subnav parameter];
如何将这些参数传递给没有代码隐藏的aspx页面?
How do you pass those parameters to an aspx page that doesn't have a codebehind?
推荐答案
您使用ViewModel
类传输数据:
public class IndexViewModel
{
public string MainNav { get; set; }
public string SubNav { get; set; }
public IndexViewModel(string mainnav, string subnav)
{
this.MainNav = mainnav;
this.SubNav = subnav;
}
}
然后您的操作方法就会出现
Your action method then comes out
public ActionResult Index(string mainnav, string subnav)
{
return View(new IndexViewModel(mainnav, subnav));
}
这意味着必须对您的视图进行强式输入:
This means your view has to be strongly typed:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<YourNameSpace.IndexViewModel>" %>
在您看来,您可以像这样输出数据:
In your view, you output the data like so:
myobj.mainnav = <%: Model.MainNav %>;
如果您使用MVC3,则另一种解决方案是使用动态ViewBag
:
An alternative solution if you use MVC3, would be to use the dynamic ViewBag
:
public ActionResult Index(string mainnav, string subnav)
{
ViewBag.MainNav = mainnav;
ViewBag.SubNav = subnav;
return View();
}
可以在页面中这样访问:
which would be accessed in the page as so:
myobj.mainnav = <%: ViewBag.MainNav %>;
但是,我建议您阅读不引人入胜的javascript ,看看您是否可以改进您的设计可以避免出现此特定问题.
However, I would recommend that you read up on unobtrusive javascript and see if you can improve your design to avoid this specific problem.
这篇关于MVC:传递参数以查看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!