在Asp.net core 6中,要使用字典进行模型数据绑定,可以按照以下步骤操作:
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
}
[HttpPost]
public IActionResult Submit(Dictionary model)
{
string username, password;
if (model.TryGetValue("Username", out username) && model.TryGetValue("Password", out password))
{
return Content($"Username:{username}, Password:{password}"); // 返回绑定的数据
}
return Content("Binding fail"); // 绑定失败
}
值得注意的是,如果表单中的name值与字典中的key值不一致,绑定会失败,因此需要保证它们的一致性。