複数の機種・画面から参照する値のリストを作成するには?
2 つのフィールド (ID、名前) を含むモデルを ListValues として作成しました。これをすべてのモデルから呼び出すのが最善の方法です。ビンディングも緩めたくない。
複数の機種・画面から参照する値のリストを作成するには?
2 つのフィールド (ID、名前) を含むモデルを ListValues として作成しました。これをすべてのモデルから呼び出すのが最善の方法です。ビンディングも緩めたくない。
ViewModel が最適なソリューションになると思います。Web で任意のビュー モデルを使用したソリューションを探してください。問題が発生した場合は、コードを添えてご連絡ください。
すべてのモデルが 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>