简短的问题:有什么合适的方法来拥有共同的、网站范围内的属性:
_layout.cshtml视图和其他视图中访问同时仍然允许自定义控制器对自己的模型?
,换句话说,如何告诉asp.net:
CommonModel与_layout.cshtml一起使用长篇小说
我创建了一个示例asp.net MVC 4 webapp,默认情况下它具有HomeController和AccountController。
HomeController.cs
public ActionResult Index()
{
CommonModel Model = new CommonModel { PageTitle = "HomePage" };
return View(Model);
}BaseModel.cs
public abstract class BaseModel
{
public string AppName { get; set; }
public string Author { get; set; }
public string PageTitle { get; set; }
public string MetaDescription { get; set; }
...
}CommonModel.cs
public class CommonModel: BaseModel
{
public CommonModel()
{
AppName = Properties.Settings.Default.AppName;
Author = Properties.Settings.Default.Author;
MetaDescription = Properties.Settings.Default.MetaDescription;
}
}_layout.cshtml
@model K6.Models.BaseModel
<!DOCTYPE html>
<html>
<head>
<title>@Model.PageTitle - @Model.AppName</title>
...问题是,这种方法:
CommonModel来使_layout.cshtml识别我的自定义属性,但同时这需要大量的工作,以便在处理HTTP、显示列表等时工作。一定有别的办法可以做到的。我是asp.net MVC的新手,那么使用ViewBag的最佳方法是什么?
发布于 2016-10-29 23:29:04
我首先想到的是一些静态的东西。
public static class ServerWideData {
private static Dictionary<string, Data> DataDictionary { get; set; } = new Dictionary<string, Data>();
public static Data Get(string controllerName = "") { // Could optionally add a default with the area and controller name
return DataDictionary[controllerName];
}
public static void Set(Data data, string name = "") {
DataDictionary.Add(name, data);
}
public class Data {
public string PropertyOne { get; set; } = "Value of PropertyOne!!";
// Add anything here
}
}您可以通过调用
ServerWideData.Set(new Data() { PropertyOne = "Cheese" }, "Key for the data")在任何地方用
ServerWideData.Get("Key for the data").PropertyOne // => Cheesehttps://stackoverflow.com/questions/40322469
复制相似问题