.net 显示不同型号的输入框

aiazj4mn  于 2023-01-27  发布在  .NET
关注(0)|答案(1)|浏览(128)

我有以下两个模型类:

public partial class EmployeeInfo
{
    public string LastName { get; set; } = null!;

    public string FirstName { get; set; } = null!;

    public virtual ICollection<EmergencyInfo> EmergencyInfos { get; } = new List<EmergencyInfo>();
}

public partial class EmergencyInfo
{
     public string emailAddress { get; set; } = null!;

    public string PhoneNumber { get; set; } = null!;

    public virtual EmployeeInfo EmployeeInfo { get; set; } = null!;
}

我创建新员工的Razor视图如下所示:

@model AckPackage.Models.EmployeeInfo
@{
    ViewData["Title"] = "Create";
}

  <div class="form-group row">
                <div class="col-sm-4">
                    <label asp-for="LastName" class="control-label"></label>
                    <input asp-for="LastName" class="form-control input-lg" />
                    <span asp-validation-for="LastName" class="text-danger"></span>
                </div>
                <div class="col-sm-4">
                    <label asp-for="FirstName" class="control-label"></label>
                    <input asp-for="FirstName" class="form-control input-lg" />
                    <span asp-validation-for="FirstName" class="text-danger"></span>
                </div>
  </div>

我可以在上面的视图中显示emeregencyInfo、emailAddress和电话号码的输入框吗?我想在同一个EmployeeInfo视图中显示emailAddress和PhoneNumber的输入框,以便用户输入他们的信息。
任何帮助都将不胜感激。

8dtrkrch

8dtrkrch1#

您可以创建一个复合类,并将其作为数据模型传递给视图:

public class Info
{
    public EmployeeInfo? Employee { get; set; }
    public EmergencyInfo? Emergency { get; set; }
}

视图代码:

@model Info;
@{
    ViewData["Title"] = "Create";
}
<form method="post" asp-action="Create">
    <div class="form-group row">
        <div class="col-sm-4">
            <label asp-for="@Model.Employee.LastName" class="control-label"></label>
            <input asp-for="@Model.Employee.LastName" class="form-control input-lg" />
            <span asp-validation-for="@Model.Employee.LastName" class="text-danger"></span>
        </div>
    ...
    <button type="submit">Save</button>
</form

在控制器端:

[HttpPost]
public IActionResult Create(Info data)
{
    // Processing the entered data 
    ....

    return View(data);
}

相关问题