Ajax与ViewComponent [英] Ajax with ViewComponent
问题描述
如何在Asp.Net Core中将AJAX用于ViewComponent?也就是说,调用方法@Component.Invoke ("ComponentName", SomeData);
的ViewComponent将涉及取决于SomeData
的各种视图,而无需重新启动主视图.
How to use AJAX for ViewComponent in Asp.Net Core? That is calling the method @Component.Invoke ("ComponentName", SomeData);
ViewComponent will involve various views depending on SomeData
without rebooting the main view.
更新
我的解决方法是:
$(function () {
$(Container).load('ControllerName/ControllerAction', {
ArgumentName: ArgumentValue });
});
控制器:
public IActionResult ControllerAction(string value)
{
return ViewComponent("ViewComponent", value);
}
在以前的版本中,有没有一种方法可以直接将ViewComponent用作AjaxHelpers?
Is there a way to directly use a ViewComponent as AjaxHelpers in previous versions?
推荐答案
您的解决方案是正确的. 从文档中获取:
Your solution is correct. From the docs:
[ViewComponents]不能作为HTTP端点直接访问,它们是从您的代码中调用的(通常是在视图中).视图组件从不处理请求.
[ViewComponents are] not reachable directly as an HTTP endpoint, they're invoked from your code (usually in a view). A view component never handles a request.
虽然视图组件未定义控制器之类的终结点,但您可以轻松地执行返回ViewComponentResult内容的控制器操作.
While view components don't define endpoints like controllers, you can easily implement a controller action that returns the content of a ViewComponentResult.
So as you suggested, a lightweight controller can act as an AJAX proxy to our ViewComponent.
public class MyViewComponentController : Controller
{
[HttpGet]
public IActionResult Get(int id)
{
return ViewComponent("MyViewComponent", new { id });
}
}
这篇关于Ajax与ViewComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!