0

如何创建由多个模型/屏幕引用的值列表?

我创建了一个模型作为 ListValues,它将包含 2 个字段(ID、名称),我希望我的所有模型都调用它,这可能是最好的方法。我也不想放松绑定。

4

2 回答 2

0

让您的所有模型都从 ListValues 继承。您可能希望将现在是基类的 ListValues 重命名为更具描述性的名称,例如 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; }
    }
}

家庭控制器.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>
于 2013-08-19T03:16:53.237 回答
0

我认为 ViewModel 将是您最好的解决方案,请在网上查找使用任何视图模型的解决方案...如果您遇到任何困难,请使用代码来找我们

于 2013-08-19T03:30:08.273 回答