- Item 1
- Item 2
- Item 3
- Item 4
using System.Collections.Generic;
namespace YourNamespace.Models
{
public class ItemModel
{
public List Items { get; set; }
}
}
using System.Xml.Linq;
using Microsoft.AspNetCore.Mvc;
using YourNamespace.Models;
namespace YourNamespace.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
var xmlPath = "items.xml";
var doc = XDocument.Load(xmlPath);
var items = doc.Element("items").Elements("item");
var model = new ItemModel
{
Items = new List()
};
foreach (var item in items)
{
model.Items.Add(item.Value);
}
return View(model);
}
}
}
@model YourNamespace.Models.ItemModel
@{
ViewData["Title"] = "Items";
}
Items
@Html.DropDownListFor(m => m.Items[0], new SelectList(Model.Items))
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
运行应用程序并访问控制器和视图的 URL,即可看到从 XML 文件中加载的数据显示在下拉框中。