使用API 数据填充MVC中的Dropdown

问题描述 投票:0回答:1

我对MVC比较新,但仍然感到困惑,因此我需要帮助解决问题。

我创建了一个web scraper控制台应用程序,我在其中比较了两篇文章(我从某个API获取数据),现在我想让这个MVC项目,我有两个下拉列表需要填充上面的数据提到的API,以便我可以比较这两篇文章。

对我来说不幸的是,我不知道如何填充这些下拉菜单,也就是说,我不知道控制器和模型中的逻辑是什么......有人可以给我一个提示或推荐一个好读,因为我完全迷失了。

提前致谢!

编辑:像这样:MVC app

c# api model-view-controller html.dropdownlistfor selectlistitem
1个回答
0
投票

填充下拉列表的一种方法是使用ViewData。

假设您对API的调用位于单独的服务中。 API需要返回List。在此示例中,List将是一个自定义类:List<CustomClass>。假设您的自定义类包含属性Id和属性Name。你的控制器看起来像:

public class HomeController : Controller
{
    private readonly IApiService _apiService;

    public HomeController(
        IApiService apiService)
    {
        _apiService = apiService;
    }

    public IActionResult Index()
    {
        // Get the data from the API into the ViewData
        // In this example, Id will be the Id of the dropdown option,
        // and the Name will be what's displayed to the user

        ViewData["DataFromArticle1"] = new SelectList(
                await _apiService.GetDataFromArticle1Async(), 
                "Id", "Name");

        ViewData["DataFromArticle2"] = new SelectList(
                await _apiService.GetDataFromArticle2Async(), 
                "Id", "Name");

        return View();
    }
}

现在,填充视图中的下拉列表:

<select asp-items="ViewBag.DataFromArticle1"></select>
<select asp-items="ViewBag.DataFromArticle2"></select>

UPDATE

以下代码将通过AJAX调用您的API端点。我们假设您创建了一个WebApi,并且在您的WebAPI中,您有一个ArticleDataController,其方法称为GetDataFromArticle1

你的观点:

<select id="dataFromArticle1"></select>

你的JavaScript:

$(document).ready(function () {  
    $.ajax({  
        type: "GET",  
        url: "/api/ArticleData/GetDataFromArticle1",   
        success: function (data) {  
            var s = '<option value="-1">Please Select a Department</option>';  
            for (var i = 0; i < data.length; i++) {  
                s += '<option value="' + data[i].Id+ '">' + data[i].Name + '</option>';  
            }  
            $("#dataFromArticle1").html(s);  
        }  
    });  
});  
© www.soinside.com 2019 - 2024. All rights reserved.