1

Models1つは にIndex view、もう 1 つは に、 2 つの異なる を送信する必要があります_Layout.cshtml。どうすればよいですか?

私のHomeController

[Route("")]
public ActionResult Index()
{
    HomeViewModel model = new HomeViewModel();
    model.A = _repoA.GetLatest(4);
    model.B = _repoB.GetLatest(4);
    model.C = _repoC.GetLatest(4);
    return View(model);
}

ViewBag, & ...を使用するのは好きではありません。ViewDataモデルを に渡すのと同じ方法でモデルを渡す方法を探していViewsます。

4

2 に答える 2

1

ViewBag で送信する必要があります。最善の策は、抽象コントローラーを作成することであることがわかりました。

public abstract class ApplicationController : Controller
{
    protected ApplicationController()
    {
         UserStateViewModel = new UserStateViewModel();
         //Modify the UserStateViewModel here.
         ViewBag["UserStateViewModel"] = UserStateViewModel;
    }

    public UserStateViewModel UserStateViewModel { get; set; }
}

次に、すべてのコントローラーにこの抽象コントローラーを継承させます。

あなたの _Layout.cshtml (またはあなたがそれを呼んだもの) に、上部に以下を含める必要があります:

@{
     var userState = (UserStateViewModel)ViewBag.UserStateViewModel;
}

重複していますが、ASP.NET MVC Razor pass model to layoutに対する 2 番目の回答から洗練されています。

于 2016-03-09T21:24:22.993 に答える