新聞中心
在ASP.NET Core中,你可以在視圖中使用@model關鍵字來獲取多個模型。,,``cshtml,@model Tuple,`,,你可以使用Model.Item1和Model.Item2`來訪問這兩個模型的屬性。
在cshtml中獲取多個model,可以通過以下方法:

創(chuàng)新互聯(lián)建站是一家專業(yè)提供赤坎企業(yè)網(wǎng)站建設,專注與成都網(wǎng)站設計、成都做網(wǎng)站、HTML5建站、小程序制作等業(yè)務。10年已為赤坎眾多企業(yè)、政府機構(gòu)等服務。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡公司優(yōu)惠進行中。
1、使用ViewBag或ViewData
在控制器中,可以將需要傳遞給視圖的數(shù)據(jù)存儲在ViewBag或ViewData中,在cshtml中,可以直接使用這些數(shù)據(jù)。
在控制器中:
public IActionResult Index()
{
ViewBag.Model1 = new Model1();
ViewBag.Model2 = new Model2();
return View();
}
在cshtml中:
@{
var model1 = ViewBag.Model1 as Model1;
var model2 = ViewBag.Model2 as Model2;
}
2、使用元組(Tuple)
在控制器中,可以將多個model組合成一個元組,然后將元組傳遞給視圖,在cshtml中,可以解構(gòu)元組以獲取各個model。
在控制器中:
public IActionResult Index()
{
var model1 = new Model1();
var model2 = new Model2();
var models = (model1, model2);
return View(models);
}
在cshtml中:
@model Tuple@{ var model1 = Model.Item1; var model2 = Model.Item2; }
3、使用自定義的ViewModel
創(chuàng)建一個包含多個model屬性的ViewModel類,然后在控制器中將ViewModel實例傳遞給視圖,在cshtml中,可以直接使用ViewModel中的屬性。
創(chuàng)建一個ViewModel類:
public class MyViewModel
{
public Model1 Model1 { get; set; }
public Model2 Model2 { get; set; }
}
在控制器中:
public IActionResult Index()
{
var viewModel = new MyViewModel
{
Model1 = new Model1(),
Model2 = new Model2()
};
return View(viewModel);
}
在cshtml中:
@model MyViewModel
@{
var model1 = Model.Model1;
var model2 = Model.Model2;
}
相關問題與解答:
1、問題:如何在cshtml中同時使用多個model?
解答:可以通過使用ViewBag、ViewData、元組或自定義的ViewModel來在cshtml中同時使用多個model。
2、問題:在cshtml中使用多個model的最佳實踐是什么?
解答:最佳實踐是使用自定義的ViewModel,這樣可以更好地組織和管理多個model,提高代碼的可讀性和可維護性。
當前題目:cshtml如何獲取多個model
標題路徑:http://m.fisionsoft.com.cn/article/cddpgjo.html


咨詢
建站咨詢
