ASP.NET MVC-将外部模型传递给编辑器模板 [英] ASP.NET MVC - Pass outer model to editor template

查看:91
本文介绍了ASP.NET MVC-将外部模型传递给编辑器模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为大多数表单使用自定义编辑器模板,但是在尝试使用它们来呈现自定义对象选择器时,我发现没有简单的方法将包含上下文的信息传递给编辑器模板.

I'm using custom editor templates for most of my forms, but while attempting to use them to render a custom object picker I've found no easy way to pass information about the containing context to the editor template.

具体来说,我的主窗体为域对象提供了一个编辑,而编辑器模板需要呈现一个AJAX选择器,该选择器包含依赖于域对象ID的对象列表.我目前正在使用additionalViewData参数传递ID,我认为该参数容易出错,因此非常难看.

Specifically, my main form renders an edit for a domain object, and the editor template needs to render an AJAX picker which contains a list of objects which are dependent on the ID of the domain object. I'm passing the ID using the additionalViewData parameter currently, which I think is error prone and therefore quite ugly.

我的表单包含类似于以下内容的代码:

My form contains code similar to the following:

@Html.EditorFor(model => model.CategoryId, new { id = model.id })

编辑器模板包含如下代码:

The editor template contains code like the following:

@{
var domainObjectId = ViewData["id"] as int?;
}

我正在使用自定义的ModelMetadataProvider选择对象选择器编辑器模板,并希望使用类似的技术将有关包含模型的信息传递给编辑器模板,但这似乎是不可能的.

I'm using a custom ModelMetadataProvider to select the object picker editor template, and hope to use a similar technique to pass information about the containing model to the editor template, but that doesn't seem be possible.

所以,我的问题是:

  1. 反正有没有使用ModelMetadataProvider将有关包含模型的信息传递到编辑器模板的方法?
  2. 如果没有,除了通过弱类型的additionalViewData参数传递每条附加信息之外,还有什么更整洁/更轻松的方法来实现我的目标?
  1. Is there anyway to use a ModelMetadataProvider to pass information about the containing model to the editor template?
  2. If not, is there any neater/easier way to achieve what I'm attempting, aside from passing every piece of additional information via the weakly typed additionalViewData parameter?

提前谢谢!

推荐答案

您需要了解,EditorTemplates设计为特定于类型的,而不是特定于上下文的.使用AdditionalViewData参数对此进行了一些思考,但这是您将获得的最好的结果.

You need to understand that EditorTemplates are designed to be type specific, not context specific. Some thought was given to this with the AdditionalViewData parameter, but that's the best you're going to get.

如果您担心类型安全,请改用ViewBag,它是围绕ViewData的类型安全的动态包装器.

If you're concerned about type safety, use ViewBag instead, which is a type-safe dynamic wrapper around ViewData.

@{
    var domainObjectId = ViewBag.Id;
}

这篇关于ASP.NET MVC-将外部模型传递给编辑器模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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