Home > Enterprise >  displaying the input box for a different model
displaying the input box for a different model

Time:01-26

I have following two model classes:

 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!;
}

My Razor view to create a new employee looks like this:

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

  <div >
                <div >
                    <label asp-for="LastName" ></label>
                    <input asp-for="LastName"  />
                    <span asp-validation-for="LastName" ></span>
                </div>
                <div >
                    <label asp-for="FirstName" ></label>
                    <input asp-for="FirstName"  />
                    <span asp-validation-for="FirstName" ></span>
                </div>
  </div>

Can I display the input box for emeregencyInfo, emailAddress and phone number in above view. I want to show both the input box for emailAddress and PhoneNumber in the same EmployeeInfo view so that users can input their information.

Any help will be highly appreciated.

CodePudding user response:

You can create a compound class and pass it to the view as data model:

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

The view code:

@model Info;
@{
    ViewData["Title"] = "Create";
}
<form method="post" asp-action="Create">
    <div >
        <div >
            <label asp-for="@Model.Employee.LastName" ></label>
            <input asp-for="@Model.Employee.LastName"  />
            <span asp-validation-for="@Model.Employee.LastName" ></span>
        </div>
    ...
    <button type="submit">Save</button>
</form

On the controller side:

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

    return View(data);
}
  • Related