Home > OS >  ASP.NET Web API with ReactJS can't get page from query
ASP.NET Web API with ReactJS can't get page from query

Time:05-11

I have a React app with ASP.NET Web API, I want to get page number from query string and make some logic but when I go to next page, the page variable in my controller is always 0 no matter that I have FromQuery attribute.

This is my controller:

[HttpGet]
public async Task<JsonResult> AllContacts([FromQuery(Name = "page")] int page)
{
    var result = await _contactsService.GetAllContactsAsync(page);
    return new JsonResult(result);
}

Here I navigate to page, this function is in Contact component which is described how I route to him in App.js:

const handlePaging = (params) => {
    navigate(`/contacts?page=${params   1}`);
    getContacts();
};

Here is implementation of getContacts function:

const getContacts = async () => {
    const request = await requester('https://localhost:7082/api/contacts', methods.get);

    const response = await request.json();

    setContacts(response);
};

This is my App.js:

function App() {
return (
<BrowserRouter>
  <div className="app">
    <Routes>
      <Route path='/' element={<Contact />} />
      <Route path='/details/:id' element={<Details />} />
    </Routes>
  </div>
</BrowserRouter>
);
}

And this is the DataGrid:

<DataGrid
                id={() => searchTerm === '' ? array.map((contact) => contact.id) : searchedContacts.map((contact) => contact.id)}
                rows={searchTerm === '' ? array : searchedContacts}
                sx={{
                    '.MuiDataGrid-columnHeaderTitle': {
                        fontWeight: 'bold',
                    },
                    '.MuiDataGrid-columnHeaders': {
                        backgroundColor: '#d3d3d3'
                    },
                    '.MuiDataGrid-row': {
                        maxHeight: '51px !important',
                        minHeight: '51px !important'
                    },
                    '.MuiDataGrid-virtualScroller': {
                        overflow: 'hidden'
                    }
                }}
                onPageChange={handlePaging}
                columns={columns}
                pageSize={10}
                rowsPerPageOptions={[10]}
                checkboxSelection
                onRowDoubleClick={e => navigateToDetails(e)}
                onSelectionModelChange={e => setEntry(e)}
            />

Please help me, I'll be grateful.

CodePudding user response:

Your request to the API doesn't actually have a page query parameter, thus, the value of the identically-named page argument of controller method will always have the default value ie. 0 in this case.

  • Related