How do I use a model as my List View datasource and add each List View entry to the model?

1 Answer 272 Views
ListView
Acadia
Top achievements
Rank 1
Iron
Acadia asked on 26 Jun 2023, 07:19 PM | edited on 27 Jun 2023, 12:02 PM

Hello,

I've searched forums and documentation and can't seem to find an example of how to do what I need.  What I am trying to do is I need an editable List View on my page where I want to use my model as the data source (in memory only).  Each time I save a record in the list view I want to add it to the model, then pass the contents of that same model to my server.

The List View will need to display all entries (update with each entry)

I need the data to persist in the model during the session.

Can anybody please point me to an example that does this in MVC C# .NET 6?

Thanks!

1 Answer, 1 is accepted

Sort by
1
Accepted
Mihaela
Telerik team
answered on 29 Jun 2023, 01:57 PM

Hello Justin,

You could create a static List collection in the Controller and use it for the CRUD operations:

//Controller
public class ListViewController : Controller
{
    public static List<OrderViewModel> tempListViewData;
}

To make the ListView editable, it is required to configure its DataSource with the respective CRUD endpoints:

//View
    @(Html.Kendo().ListView<ListViewExample.Models.OrderViewModel>()
        .Name("listView")
        ...
        .Editable()
        .DataSource(dataSource => dataSource
            .Ajax()
            .Model(m => m.Id("OrderID"))
            .Read(read => read.Action("Orders_Read", "ListView"))
            .Create(create => create.Action("Orders_Create", "ListView"))
            .Update(update => update.Action("Orders_Update", "ListView"))
            .Destroy(destroy => destroy.Action("Orders_Destroy", "ListView"))
        )
    )

You could intercept the edited/created Model instance in the Update/Create Action methods, update the static collection based on the changes and pass the required data to the remote server:

public ActionResult Orders_Create([DataSourceRequest] DataSourceRequest request,  OrderViewModel order)
{
    if (order != null && ModelState.IsValid)
    {
        // Save the new record in the tempListViewData collection
            var nextId = tempListViewData.Count + 1;
            tempListViewData.OrderID = nextId;
            tempListViewData.Add(order);
    }
    return Json(new [] { order }.ToDataSourceResult(request, ModelState));
}

For a complete example, check out the ListView Editing article:

https://docs.telerik.com/aspnet-core/html-helpers/data-management/listview/editing

If you have any questions, please share them.

 

Regards, Mihaela Progress Telerik

As of R2 2023, the default icon type will be SVG instead of Font. See this blogpost for more information.
Tags
ListView
Asked by
Acadia
Top achievements
Rank 1
Iron
Answers by
Mihaela
Telerik team
Share this question
or