如何創建要由多個模型/屏幕引用的值列表?填充來自多個模型的值列表
我已經創建了一個ListValues模型,它將包含2個字段(ID,Name),我希望被我的所有模型調用,可能是最好的方法。我也不想鬆懈。
如何創建要由多個模型/屏幕引用的值列表?填充來自多個模型的值列表
我已經創建了一個ListValues模型,它將包含2個字段(ID,Name),我希望被我的所有模型調用,可能是最好的方法。我也不想鬆懈。
所有模型都從ListValues繼承。您可能希望將ListValues(現在是基類)重命名爲更類似於ModelBase的描述。
下面是一個例子:
ModelBase.cs
namespace ListValuesTest.Models
{
public class ModelBase
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Employee : ModelBase
{
public string Department { get; set; }
}
public class Customer : ModelBase
{
public string Application { get; set; }
}
}
HomeController.cs
namespace ListValuesTest.Controllers
{
public class HomeController : Controller
{
public ActionResult EmployeeOfTheMonth()
{
ListValuesTest.Models.Employee NumberOneEmployee = new Models.Employee();
NumberOneEmployee.ID = 1;
NumberOneEmployee.Name = "Brian";
NumberOneEmployee.Department = "IT";
return View(NumberOneEmployee);
}
public ActionResult CustomerOfTheMonth()
{
ListValuesTest.Models.Customer NumberOneCustomer = new Models.Customer();
NumberOneCustomer.ID = 1;
NumberOneCustomer.Name = "Microsoft";
NumberOneCustomer.Application = "Visual Studio";
return View(NumberOneCustomer);
}
}
}
EmployeeOfTheMonth.cshtml
@model ListValuesTest.Models.Employee
@{
ViewBag.Title = "EmployeeOfTheMonth";
}
<h2>EmployeeOfTheMonth</h2>
<fieldset>
<legend>Employee</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Department)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Department)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
@Html.ActionLink("Back to List", "Index")
</p>
CustomerOfTheMonth.cshtml
@model ListValuesTest.Models.Customer
@{
ViewBag.Title = "CustomerOfTheMonth";
}
<h2>CustomerOfTheMonth</h2>
<fieldset>
<legend>Customer</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.Application)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Application)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.Name)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.Name)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
@Html.ActionLink("Back to List", "Index")
</p>
試圖這樣做,但得到的錯誤,請幫助一些代碼參考。在此先感謝 – Abhijit