如何将参数传递给 mvc 4 中的局部视图 [英] How can I pass parameters to a partial view in mvc 4

查看:30
本文介绍了如何将参数传递给 mvc 4 中的局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的链接:

 <a href='Member/MemberHome/Profile/Id'><span>Profile</span></a>

当我点击它时,它会调用这个部分页面:

and when I click on this it will call this partial page:

 @{
    switch ((string)ViewBag.Details)
    {

        case "Profile":
        {
           @Html.Partial("_Profile"); break;
        }

    }
}

部分页面_Profile包含:

Partial page _Profile contains:

Html.Action("Action", "Controller", model.Paramter) 

示例:

@Html.Action("MemberProfile", "Member", new { id=1 })   // id is always changing

我的疑问是如何将这个Id"传递给model.parameter部分?

我的控制器是:

 public ActionResult MemberHome(string id)
    {
        ViewBag.Details = id;
        return View();
    }
  public ActionResult MemberProfile(int id = 0)
    {
        MemberData md = new Member().GetMemberProfile(id);
        return PartialView("_ProfilePage",md);
    }

推荐答案

你的问题很难理解,但如果我明白了要点,你只是在你的主视图中有一些你想要在部分访问的值在该视图中呈现.

Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.

如果你只用部分名称渲染一个部分:

If you just render a partial with just the partial name:

@Html.Partial("_SomePartial")

它实际上会将您的模型作为隐式参数传递,就像您要调用一样:

It will actually pass your model as an implicit parameter, the same as if you were to call:

@Html.Partial("_SomePartial", Model)

现在,为了让你的部分能够真正使用它,它也需要有一个定义好的模型,例如:

Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:

@model Namespace.To.Your.Model

@Html.Action("MemberProfile", "Member", new { id = Model.Id })

或者,如果您要处理不在视图模型中的值(它在 ViewBag 中或视图本身以某种方式生成的值),那么您可以传递一个 ViewDataDictionary

Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary

@Html.Partial("_SomePartial", new ViewDataDictionary { { "id", someInteger } });

然后:

@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })

与模型一样,默认情况下,Razor 将隐式传递视图的局部ViewData,因此如果您的视图中有 ViewBag.Id,那么您可以引用同样的事情在你的部分.

As with the model, Razor will implicitly pass your partial the view's ViewData by default, so if you had ViewBag.Id in your view, then you can reference the same thing in your partial.

这篇关于如何将参数传递给 mvc 4 中的局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆