将模型传递到布局页面 MVC

Pass Model into Layout Page MVC

我正在使用 MVC 5 做 Web 项目。我需要将一些数据传递给布局页面(数据为 Category_id 或 Category_Name)。 我读了一些答案说我需要制作 View Model ,但我的项目必须在 MVC 而不是 MVVM 中, 你有什么想法吗? 谢谢!

你可以通过这种方式直接传递一个obj给View:

public virtual async Task<IActionResult> Index()
{
    var model = await MethodThatRedurnModel();
    return View(model);
}

您必须创建一个基础视图模型,您必须将其用于所有视图

using Microsoft.AspNetCore.Mvc.Rendering;

public interface IBaseViewModel
{
    public int CategoryId { get; set; }
    public List<SelectListItem> CategoryList { get; set; }
}

public class BaseViewModel : IBaseViewModel
{
    public int CategoryId { get; set; }
    public List<SelectListItem> CategoryList { get; set; }
}

行动

public IActionResult Index()
        {
            
var baseViewModel=new BaseViewModel();
  InitBaseViewModel(baseViewModel);
     return View(baseViewModel);
        }

private  void  InitBaseViewModel(IBaseViewModel baseViewModel)
{

    //this is  for test
    // in the real code you can use context.Categories.Select ....

    var items = new List<SelectListItem> {
            new SelectListItem {Text = "Category1", Value = "1"},
            new SelectListItem {Text = "Category2", Value = "2"},
            new SelectListItem {Text = "Category3", Value = "3"}
            };


    baseViewModel.CategoryList= items;
}

布局

@model IBaseViewModel // you can omit it but I like to have it explicitly

@if(Model!=null && Model.CategoryList!=null && Model.CategoryList.Count > 0)
{
 <select class="form-control" style="width:450px" asp-for="CategoryId" asp-items="CategoryList">
}

对于另一个视图,您可以创建此操作代码

public IActionResult MyAction()
var myActionViewModel= new MyActionViewModel {
..... your init code
}

 InitBaseViewModel(myActionViewModel);

return View(myActionViewModel)
}

public class MyActionViewModel : BaseViewModel
//or 
public class MyActionViewModel : IBaseViewModel
{
    public .... {get; set;}
}