Grid in ViewComponent JavaScript issues

1 Answer 25 Views
Grid
Ryan
Top achievements
Rank 1
Iron
Iron
Ryan asked on 08 Mar 2024, 05:11 PM | edited on 08 Mar 2024, 08:57 PM

Hello,

I am surprised this is not asked about more in the forums on using JavaScript functions in view components.

I have a grid inside a view component and am having issues getting the datasource read Data function to work so I can pass parameters from the view component's backend .cs file to my API (it says grid_getReadParameters is undefiend even though it's defined in script tag at the bottom of the view component). I have read that view components can't really have javascript or something strange like that which makes no sense. I defined a script section in my view component and it was unable to find "grid_getReadParameters". How does one define this within the view component? I do not want to have to sprinkle this around on every page which uses my view component, that would defeat the purpose. Thanks in advance for your help.

See below example:

@(Html.Kendo()
    .Grid<ViewModels.MyViewModel>()
    .Name("grid_" + uniqueId)
    .Sortable()
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Filterable()
    .ToolBar(x =>
    {
        x.Create().Text("Add New");
        x.Save().SaveText("Save").CancelText("Cancel");
    })
    .Columns(columns =>
    {
        columns.Bound(c => c.Value)
        .Width(125)
        .Filterable(ftb => ftb.Multi(true).Search(true).CheckAll(true));
    })
    .DataSource(ds => ds
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Read(r => r.Url("/api/ControllerName?handler=MethodName").Data("grid_getReadParameters"))
            .Events(events => events.Error("grid_error"))
            .PageSize(100)
            .Model(m =>
            {
                m.Field(id => id.Value).Editable(true);
            })
    )
)

Ryan
Top achievements
Rank 1
Iron
Iron
commented on 08 Mar 2024, 08:56 PM

So turns out I was able to avoid the javascript and just pass this for the URL for the read function:

/api/ControllerName/methodName?propertyName=value

The problem now is that I need to send over data items when I create and update records which requires sending complex objects so I still need javascript to work right for this without defining the javascript outside the view component

1 Answer, 1 is accepted

Sort by
0
Alexander
Telerik team
answered on 13 Mar 2024, 03:00 PM

Hi Ryan,

I noticed that you have no active license associated with your account which limits our support service overall. In this regard, I would personally recommend renewing your license if you want to proceed with getting the latest bug fixes, features, and support for the product.

Regardless, I appreciate the fact that you have taken the time to share such exhaustive explanations in terms of the employed scenario on your side.

To be quite frank with you, I did not see anything apparent with the Grid's configuration that would be causing the reported behavior at hand.

Since you are utilizing a WebAPI scenario, it is important to take into consideration the fact that the request will be molded differently as opposed to an MVC architectural scenario. This is due to the WebApi attribute as suggested by the official Microsoft resources.

Taking this into consideration, it is important to make sure that the arguments coming from the request body are annotated with the "[FromForm]" Binding attribute. 

For example:

[ApiController]
[Route("/api/grid")]
public class ApiController : Controller
{
    [HttpPost]
    public IActionResult Post([DataSourceRequest] DataSourceRequest request, [FromForm]int myId, [FromForm] RequestModel requestModel)
    {
        var result = Enumerable.Range(1, 50).Select(i => new MyViewModel
        {
            Value = i,
        });

        var dsResult = result.ToDataSourceResult(request);
        return Json(dsResult);
    }
}

This should then produce the following result once additional meta-information is supplemented:

Primitive Type Arguments:

Non-Primitive Type Arguments:

Where the handler is defined as follows:

<script>
    function grid_getReadParameters() {
        return {
            myId: 5,
            requestModel: {
                RequestMethod: "POST"
            }
        }
    }
</script>

Generally, we have a readily available example in our GitHub repository that showcases such a scenario that you might find intriguing which I have further extended with this scenario.

GitHub Repository - https://github.com/telerik/ui-for-aspnet-core-examples

Here are the relevant code compartments that play a foundational role in this scenario:

Please give this suggestion a try and let me know how it works out for you.

Kind Regards,
Alexander
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages. If you're new to the Telerik family, be sure to check out our getting started resources, as well as the only REPL playground for creating, saving, running, and sharing server-side code.
Ryan
Top achievements
Rank 1
Iron
Iron
commented on 13 Mar 2024, 03:50 PM

Hi, my issue is strictly with where to define the javascript within a view component for the get read parameters? If I put a script tag at the bottom of the view component the grid is printing errors that the function is not defined yet it is.
Ryan
Top achievements
Rank 1
Iron
Iron
commented on 13 Mar 2024, 03:51 PM

Thank you for the lengthy response though. I ended up figuring out how to use Web API with this but I just need to find out how to define javascript in the view component for the grid. I had to add a js file to my _layout in order for the javascript to be found but I want the javascript to be self-contained within the view component itself.
Alexander
Telerik team
commented on 18 Mar 2024, 12:18 PM

Hi Ryan,

When our components are used in partial views for example in a ViewComponent - as it operates much like the partial view, but with additional features. The event handlers must precede the component's declaration.

So instead of having the handlers in a script below the components, I would suggest moving the script that contains the handlers to the top of the page:

<script>
    function grid_getReadParameters() {
        return {
            myId: 5,
            requestModel: {
                RequestMethod: "POST"
            }
        }
    }

</script>
@(Html.Kendo()
    .Grid<MyViewModel>()
    .Name("grid_" + Guid.NewGuid().ToString())
	...
)

In addition to this, I am also attaching a runnable sample for you to examine further.

Tags
Grid
Asked by
Ryan
Top achievements
Rank 1
Iron
Iron
Answers by
Alexander
Telerik team
Share this question
or