在MVC做局部视图继承其父视图模型? [英] In MVC do partial views inherit the models of their Parent views?

查看:226
本文介绍了在MVC做局部视图继承其父视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递一些数据视图从我的控制器,我想这里面查看局部视图中显示(不要问,这是复杂的)。我知道我可能甚至不应该传递模型到的inded另一个视图的观点,但我注意到,部分观点实际上是继承了parenmt视图的模型:

 公众的ActionResult指数(){ 人p =新的Person
 {
    FName参数=墨子,
    LName的=九月 }; 返回查看(P);

}

然后我里面的首页查看我有:

 < H2>指数< / H>@ Html.Partial(_ IndexPartial)

和内幕 _IndexPartial 我有:

  @ Model.FName

和本打印墨子。

这是有意的行为一样,在那里WPF子控件继承父视图的数据上下文?而且是它认为不好的做法,在应用程序中使用它?

感谢。


解决方案

  

这是有意的行为一样,在那里WPF的子控件
  继承父视图的数据上下文?


是的。

我看你是不是目前传递任何模式向
将它的工作只是继承布局,再不需要使用部分呢?

如果你想继续使用它像你,也许只是更明确一下,而目前的模式传递给部分。

  @ Html.Partial(_ IndexPartial模型)

如果你看一下源Html.Partial(视图):

 公共静态MvcHtmlString部分(此的HtmlHelper的HtmlHelper,串partialViewName)
{
    返回部分(的HtmlHelper,partialViewName,空/ *型号* /,htmlHelper.ViewData);
}

它是通过htmlHelper.ViewData传递模型,您可以访问该模型以同样的方式在您的视图与@ {} ViewData.Model,但这是的的一个很好的做法。

I'm passing some data to a View from my controller, which I wish to display inside a partial view inside that View (don't ask, it's complicated). I know I probably shouldn't even be passing a model to a view that's inded for another view, but I've noticed that the partial view is actually inheriting the Model from the parenmt View:

public ActionResult Index(){

 Person p = new Person
 {
    FName = "Mo",
    LName = "Sep"

 };

 return View(p);

}

Then inside my Index View I have:

<h2>Index</h2>

@Html.Partial("_IndexPartial")

and Inside _IndexPartial I have:

@Model.FName 

and this Prints "Mo".

Is this behaviour intended like that in WPF where child controls inherit the data context of their parent View? And is it considered bad practise to use this in your application?

Thanks.

解决方案

Is this behaviour intended like that in WPF where child controls inherit the data context of their parent View?

Yes.

I see you are not currently passing any model to the Would it work to just inherit the layouts, and then not need to use the partial at all?

If you want to keep using it like you are, maybe just be more explicit about it, and pass the current model to the partial.

@Html.Partial("_IndexPartial", Model)

If you look at the source for Html.Partial(view):

public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName)
{
    return Partial(htmlHelper, partialViewName, null /* model */, htmlHelper.ViewData);
}

It is passing the model via htmlHelper.ViewData, you can access the model in the same way in your view with @{ViewData.Model}, but this is NOT a good practice.

这篇关于在MVC做局部视图继承其父视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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