Ajax with ViewComponent

ⅰ亾dé卋堺 提交于 2020-01-14 08:04:21

问题


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.

Update

My solution is:

$(function () {
      $(Container).load('ControllerName/ControllerAction', {
                ArgumentName: ArgumentValue });
                                                 });

Controller :

public IActionResult ControllerAction(string value)
        {
           return ViewComponent("ViewComponent", value);
        }

Is there a way to directly use a ViewComponent as AjaxHelpers in previous versions?


回答1:


Your solution is correct. From the docs:

[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.

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 });
    }
}


来源:https://stackoverflow.com/questions/36529424/ajax-with-viewcomponent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!