使用两个单独的模型在ASP.NET上创建表单

时间:2017-06-12 17:44:39

标签: c# html asp.net-mvc razor

我正在使用Visual Studio 2017,其中包含最新的更新。 我正在尝试输入一个带有一些普通文本框回答问题的表单以及一个复选框答案问题,并将所有答案记录在同一个数据库中。我的问题的一部分是如何让两个单独的模型使用单独的数据库作为单个控制器的参考,并将一个数据库记录中的所有问题答案的列表视为一个视图?也许我会以错误的方式解决这个问题,因为我是ASP.NET新手,这很有可能。对此问题的任何意见都将不胜感激......

以下是我的两个模型的代码:

模型I:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace TessituraForm
{
    public class TessituraFormContext : DbContext
    {
        public TessituraFormContext(DbContextOptions<TessituraFormContext> options) : base(options)
        {

        }
        public DbSet<Models.Roles> Roles { get; set; }
    }
}

模型II:

using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;

namespace TessituraForm.Models
{
    public class Applicant
    {
        public int ID { get; set; }

        [Display(Name = "Full Name:")]
        [DataType(DataType.Text)]
        [Required]
        public string FullName { get; set; }

        [Display(Name = "SI User Name:")]
        [StringLength(10)]
        [DataType(DataType.Text)]
        [Required]
        public string SIUserName { get; set; }

        [Display(Name = "Supervisor:")]
        [Required]
        public string Supervisor { get; set; }

        [Display(Name = "Badge Number:")]
        [StringLength(8)]
        [DataType(DataType.Text)]
        [Required]
        public string BadgeNumber { get; set; }

        [Display(Name = "Badge Expiration Date:")]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
        [Required]
        public DateTime BadgeExpirationDate { get; set; }


        [Display(Name = "Applicant is a(n):")]
        [DataType(DataType.Text)]
        [Required]
        public string ApplicantIsAn { get; set; }

    }
    public class Roles
    {
        [Key]
        public int ID { get; set; }
        public string AdvancementFundraising { get; set; }
        public string CustomerService { get; set; }
        public string DiscoveryTheater { get; set; }
        public string BusinessOffice { get; set; }
        public string CustomerServiceSupport { get; set; }
        public string ExecutiveStaff { get; set; }
        public string Marketing { get; set; }
        public string Programming { get; set; }
        public string VolunteerCoordinator { get; set; }

        public bool CheckboxAnswer { get; set; }
    }
}

控制器代码:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;
using TessituraForm.Models;

namespace Applicant.Controllers
{
    public class ApplicantController : Controller
    {
        private readonly TessituraFormContext _context;

        public ApplicantController(TessituraFormContext context)
        {
            _context = context;    
        }

        // GET: Applicants
        public async Task<IActionResult> Index()
        {
            return View(await _context.Applicant.ToListAsync());
        }

        // GET: Applicants/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var applicant = await _context.Applicant
                .SingleOrDefaultAsync(m => m.ID == id);
            if (applicant == null)
            {
                return NotFound();
            }

            return View(applicant);
        }

        // GET: Applicants/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Applicants/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,FullName,SIUserName,Supervisor,BadgeNumber,BadgeExpirationDate,ApplicantIsAn,Roles")] Applicant applicant)
        {
            if (ModelState.IsValid)
            {
                _context.Add(applicant);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(applicant);
        }

        // GET: Applicants/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var applicant = await _context.Applicant.SingleOrDefaultAsync(m => m.ID == id);
            if (applicant == null)
            {
                return NotFound();
            }
            return View(applicant);
        }

        // POST: Applicants/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,FullName,SIUserName,Supervisor,BadgeNumber,BadgeExpirationDate,ApplicantIsAn,Roles")] Applicant applicant)
        {
            if (id != applicant.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(applicant);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ApplicantExists(applicant.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(applicant);
        }

        // GET: Applicants/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var applicant = await _context.Applicant
                .SingleOrDefaultAsync(m => m.ID == id);
            if (applicant == null)
            {
                return NotFound();
            }

            return View(applicant);
        }

        // POST: Applicants/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var applicant = await _context.Applicant.SingleOrDefaultAsync(m => m.ID == id);
            _context.Applicant.Remove(applicant);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool ApplicantExists(int id)
        {
            return _context.Applicant.Any(e => e.ID == id);
        }
    }
}
namespace DatabaseContext.Controllers
{
    public class DatabaseContextController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Roles()
        {
            Applicant objApplicant = newApplicant();
        }
    }
}

查看索引代码:

@model IEnumerable<TessituraForm.Models.Applicant>

@{
    ViewData["Title"] = "Index";
}
<style>
    body {
        background-color: lightgray;
    }

    h2 {
        color: black;
        margin-left: 5px;
    }
</style>

<img src="~/Images/TSA.jpg" alt="TSA" style="position:absolute;left:1372px;top:57px;width:150px;height:75px;" />

<h2>Index</h2>

<p>
    <a asp-action="Create" style="margin-left:20px;">Create New</a>
</p>
<table class="table" border="1">
    <thead>
        <tr>
                <th>
                    @Html.DisplayNameFor(model => model.FullName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.SIUserName)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Supervisor)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.BadgeNumber)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.BadgeExpirationDate)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.ApplicantIsAn)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Roles)
                </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FullName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.SIUserName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Supervisor)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BadgeNumber)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BadgeExpirationDate)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ApplicantIsAn)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Roles)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.ID">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

同样,我的目标只是在网页上有一个表单,其中包含一个带有普通文本框答案的部分和一个复选框部分。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以做的是创建一个新的Model,然后将其他两个放在下面的那个:

public class YourNewModel
{
    public Applicant Applicant {get;set;} //note you can declare it here as a List or any how you want
    public Roles Roles {get;set;}
}

注意 这只是为了给你一个想法并开始你的意思,这也意味着改变你Controller方法中的方法。 您还必须将此Model传递给您的视图,这样您就可以将两个模型放在同一个地方。

我希望这会有所帮助