Asp.Net MVC 5如何发送到ViewBag管窥 [英] Asp.Net MVC 5 How to send ViewBag to Partial View

查看:128
本文介绍了Asp.Net MVC 5如何发送到ViewBag管窥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个_LoginPartial查看并希望通过ViewBag将数据发送到它,但我'发送数据的控制器,没有一个视图。

I have a _LoginPartial View and want to send data to it by ViewBag, but the Controller that I'am sending data from, doesn't have a View.

public PartialViewResult Index()
    {
        ViewBag.sth = // some data
        return PartialView("~/Views/Shared/_LoginPartial.cshtml");
    }

这code并没有为我工作。

This code didn't work for me.

推荐答案

看来你希望当你被称为该首页的行动: @ Html.Partial('_ LoginPartial')。这将永远不会发生。 部分只是贯穿剃刀的当前视图的上下文的局部视图,并吐出生成的HTML。

It seems you're expecting this Index action to be called when you do: @Html.Partial('_LoginPartial'). That will never happen. Partial just runs the partial view through Razor with the current view's context and spits out the generated HTML.

如果您需要更多的信息,你的部分,你可以指定一个自定义的的ViewDataDictionary

If you need additional information for your partial, you can specify a custom ViewDataDictionary:

@Html.Partial("_LoginPartial", new ViewDataDictionary { Foo = "Bar" });

您可以在里面部分通过然后访问:

Which you can then access inside the partial via:

ViewData["Foo"]

您还可以使用儿童的行动,这是一般preferable如果有不需要的主视图背景下的局部视图工作。 _LoginPartial 似乎是一个不错的选择,虽然我不知道你使用它究竟如何。讽刺的是,虽然,配备了带个人身份验证默认MVC项目的 _LoginPartial 视图使用儿童的行动。

You can also use child actions, which is generally preferable if working with a partial view that doesn't need the context of the main view. _LoginPartial seems like a good candidate, although I'm not sure how exactly you're using it. Ironically, though, the _LoginPartial view that comes with a default MVC project with individual auth uses child actions.

基本上,code你应该已经工作,你只需要改变的 Html.Action 而不是<$ C $您如何使用引用它C> Html.Partial :

Basically, the code you have would already work, you would just need to change how you reference it by using Html.Action instead of Html.Partial:

@Html.Action("Index")

这是我们在调用的动作的通知在这里,现在的看法。

Notice that you're calling the action here and now the view.

这篇关于Asp.Net MVC 5如何发送到ViewBag管窥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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