Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax with ViewComponent

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?

like image 520
ax smotri Avatar asked Apr 10 '16 11:04

ax smotri


People also ask

Can Ajax work with ASP NET?

AJAX is used to create dynamic web pages that do not require page reloading when any part of the whole web page content or the whole web page content is changed. The server data exchange is asynchronous in nature and AJAX in ASP.net uses multiple technologies like XSLT, XHTML, CSS, JavaScript, etc.

Can we use Ajax in MVC?

The MVC Framework contains built-in support for unobtrusive Ajax. You can use the helper methods to define your Ajax features without adding a code throughout all the views. This feature in MVC is based on the jQuery features. To enable the unobtrusive AJAX support in the MVC application, open the Web.

What is view component in asp net core?

A view component consists of two parts: the class (typically derived from ViewComponent) and the result it returns (typically a view). Like controllers, a view component can be a POCO, but most developers take advantage of the methods and properties available by deriving from ViewComponent .

What is the use of Ajax in dot net framework?

AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


1 Answers

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 });
    }
}
like image 52
Shaun Luttin Avatar answered Sep 22 '22 10:09

Shaun Luttin