MVC: pass parameter to view?

后端 未结 5 436
梦谈多话
梦谈多话 2020-12-14 19:52

MVC newbie question:

I\'m picking up a URL of the form go/{mainnav}/{subnav}, which I\'ve successfully routed to the GoController class, me

5条回答
  •  清歌不尽
    2020-12-14 20:39

    You use a ViewModel class to transfer the data:

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

    In your view, you output the data like so:

    myobj.mainnav = <%: Model.MainNav %>;
    

    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 %>;
    

    However, I would recommend that you read up on unobtrusive javascript and see if you can improve your design to avoid this specific problem.

提交回复
热议问题