use*_*823 17 asp.net asp.net-mvc renderaction asp.net-core
我试图从我的小型ASP.NET MVC 4应用程序切换到ASP.NET Core.
在我的MVC 4应用程序中,我有一个使用RenderSection的布局文件:
@RenderSection("xyz", required: false)
Run Code Online (Sandbox Code Playgroud)
然后,在我的索引文件中,我有:
@section xyz{
@{Html.RenderAction("abc");}
}
Run Code Online (Sandbox Code Playgroud)
所以,我从Index调用控制器动作方法abc().方法abc()传递模型对象并返回具有该模型的局部视图.我无法使用RenderPartial,因为它需要传递模型.
现在,在ASP.NET Core中,我没有RenderAction()方法.
我的问题是:如何从我的索引文件中调用控制器操作方法?是否有任何其他HTML助手(虽然我没有看到任何)?
.
use*_*823 21
我终于能够用ViewComponent做到这一点.所以,我没有使用RenderAction(),而是:
@section xyz{
@await Component.InvokeAsync("abc")
}
Run Code Online (Sandbox Code Playgroud)
其中abc是一个类为abcViewComponent.ViewComponent看起来像:
public class abcViewComponent : ViewComponent
{
private DbContextOptions<MyContext> db = new DbContextOptions<MyContext>();
public async Task<IViewComponentResult> InvokeAsync()
{
MyContext context = new MyContext(db);
IEnumerable<tableRowClass> mc = await context.tableRows.ToListAsync();
return View(mc);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我在一个新文件夹'mc'下创建了一个视图作为Views/Home/Components/mc/Default.cshtml
需要注意的是,视图名称是Default.cshtml,这就是它的工作原理.如果有人有任何更好的解决方案,请告诉我.
感谢您指向ViewComponent的方向.
小智 6
有一个解决方法,您可以使用 Url.Action + JQuery 来呈现内容。
您想要呈现动作的视图将如下所示:
<div id="dynamicContentContainer"></div>
<script>
$.get('@Url.Action("GetData", "Home")', {id : 1}, function(content){
$("#dynamicContentContainer").html(content);
});
</script>
Run Code Online (Sandbox Code Playgroud)
家庭控制器:
[HttpGet]
public IActionResult GetData(int id)
{
return PartialView(id);
}
Run Code Online (Sandbox Code Playgroud)
风景
<div id="dynamicContentContainer"></div>
<script>
$.get('@Url.Action("GetData", "Home")', {id : 1}, function(content){
$("#dynamicContentContainer").html(content);
});
</script>
Run Code Online (Sandbox Code Playgroud)
如果您想更好地控制请求,您可以在此处阅读更多信息:jQuery.get()
只是为了完成上述问题,传递ViewComponent类的名称可能更安全,如下所示:
@section xyz{
@await Component.InvokeAsync(nameof(yournamespace.abc))
}
Run Code Online (Sandbox Code Playgroud)
虽然通常使用"Default"作为结果视图,但如果视图名称与默认值不同,也可以返回视图名称:
public class abcViewComponent : ViewComponent
{
private DbContextOptions<MyContext> db = new DbContextOptions<MyContext>();
public async Task<IViewComponentResult> InvokeAsync()
{
MyContext context = new MyContext(db);
IEnumerable<tableRowClass> mc = await context.tableRows.ToListAsync();
return View("YourViewName", mc);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
18481 次 |
最近记录: |