Home How to Handle Loading Data Based on Selection in MVC?
Reply: 1

How to Handle Loading Data Based on Selection in MVC?

VSO
1#
VSO Published in 2017-12-06 17:58:36Z

I have always worked with Web APIs, so I don't know how to handle this very basic problem in .NET Core MVC (I am only familiar with MVC conceptually). My problem:

I need a user to select an option from a dropdown on the front end and then show some data based on the option (after fetching it).

If I were writing an SPA consuming an API, I would simply make a call to the backend to get the data and then generate the html to display it on the front end.

How is this handled in MVC? Isn't the convention to return entirely new views? How are things like these handled?

I just need a pointer in the right direction conceptually - I can figure out the code.

Edit: Should I just pretend it's an SPA despite it being a view and create an API endpoint in the same app that provides the view and consume it from the cshtml?

Chris Pratt
2#
Chris Pratt Reply to 2017-12-06 18:14:57Z

It works exactly the same way. You make an AJAX call to fetch some data. You can either return the data directly, and utilize JS to render the HTML or return HTML directly. Either way, you use the AJAX callback to replace the appropriate content on the page.

Even in older ASP.NET MVC projects it worked this way, though you basically had to decide whether you were going to use an MVC controller or a Web Api controller to do the work. Either would work, but there were advantages/disadvantages to each approach. MVC/Web Api could always coexist in the same project.

In ASP.NET Core, the difference is purely semantic. There's really no such thing as MVC and Web Api anymore - just ASP.NET Core. A controller is a controller is a controller, so just add an endpoint and go to town.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314624 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO