我正在尝试使用 .net Core ViewComponents 而不是部分 View 。这是我的场景。 我有一个包含一些剑道列表框控件的 View 。当单击任何列表框中的项目时,我需要使用列表框中选定的项目 ID 调用 Web 组件。我还需要保持 ViewComponents 隐藏,直到用户单击列表框项目。每个列表框都有自己的 ViewComponent,因为每个列表框的 View 组件中的控件都不同。因此,我必须隐藏一些 View 组件并仅显示列表框的相关组件。我不知道如何在选择任何列表框中的项目 id 时将其传递给 Invoke 方法。
这是我的主要 View (删除了非必要代码)
<div style="height:25%; width:100%; background-color:antiquewhite;">
<b>Sections:</b>
@(Html.Kendo().ListBox()
.Name( "SectionListBox" )
.Selectable( ListBoxSelectable.Single )
.DataTextField( "Name" )
.DataValueField( "id" )
//.DataSource( ds => ds.Read( r => r.Action( "GetAllPageSectionsAsync", "Home" ) ) )
.Events( e => e.Change( "onSectionSelected" ) )
.HtmlAttributes( new { style = "width:95%;height:85%;" } )
)
</div>
<div style="height:25%; width:100%; background-color:cornsilk;">
<b>Fields:</b>
@(Html.Kendo().ListBox()
.Name( "FieldListBox" )
.Selectable( ListBoxSelectable.Single )
.DataTextField( "Name" )
.DataValueField( "id" )
//.DataSource( ds => ds.Read( r => r.Action( "GetAllFieldsAsync", "Home" ) ) )
.HtmlAttributes( new { style = "width:95%;height:85%;" } )
)
</div>
<div class="col-md-8" style="height:100%">
<div class="col-md-12" style="height:100%;">
<div id="AttrGridDiv" class="col-md-5" style="height:40%;">
<label>Attributes</label>
@await Component.InvokeAsync( "PageAttributes", new { pageId = 123 } )
</div>
</div>
</div>
这是我的组件 View :
@model IEnumerable<aaaaaaaa>
@(Html.Kendo().Grid<dynamic>()
.Name( "Attributes" )
.Selectable()
.Sortable()
.Scrollable()
.Events( e => e.Change( "onAttributeGridSelected" ) )
.HtmlAttributes( new { style = "width:100%;" } )
//.DataSource( ds => ds
//.Ajax()
//.Read( r => r.Action( "GetPages", "Home" ).Type( HttpVerbs.Post ) ) )
)
这是我的 View 组件:
[ViewComponent(Name ="PageAttributes")]
public class PageAttibutesViewComponent : ViewComponent
{
private IRulesEngineService reService;
public PageAttibutesViewComponent( IRulesEngineService _reService)
{
reService = _reService;
}
public async Task<IViewComponentResult> InvokeAsync(int pageId)
{
var pageAttribs = await reService.GetAllPageAttributesAsync( pageId );
return View( pageAttribs );
}
}
我只展示了其中一个组件。我有一些类似的组件,我需要根据选择的列表框来调用这些组件将呈现不同的控件。
所以,我的问题是:
- 如何有条件地从 View 中调用组件?
- 如何将选定的 ID 从选定的列表框传递到调用 方法?
最佳答案
ViewComponents
由 Razor(或支持该功能的任何替代 View 引擎)处理。您尝试实现的目标发生在浏览器中,但您还需要一些服务器端处理。
正如我所见,您必须(1)捕获 ListBox 更改(Javascript),然后(2)将其发布回 Controller (同样是 Javscript),(3)将处理请求,根据需要更改模型已提交 (C#),最后 (4) 返回模型已更改的 View ,以便 View 可以确定如何(参数值)调用有问题的 ViewComponent
(C#、Razor) 。您也可能决定返回不同的 View ,但这有点不常见。不是那么简单,但这是网络。很久以前,在 Web 表单中,复选框和下拉菜单具有属性 PostBack
(或类似属性),在选中该属性时,其作用基本相同。
实际上,发送回 Controller 、更改后的 View 模型以及最终使用更改后的模型呈现的 View 会导致 ViewComponent
的调用发生变化。
Core 2.0 中有三种类型的 ViewComponent
调用。您可以在这里阅读有关它们的信息:https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components#invoking-a-view-component .
关于c# - 如何将运行时参数传递给 ViewComponent Invoke 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47718187/