首页 > 解决方案 > 如何使用外键关系将数据从视图返回到 asp.net 中的控制器?

问题描述

有两个表 Roles 和 Administrator。我在管理员表中有一个引用 RoleId 的外键。因此,我执行 linq 查询以从 SQL 服务器获取所有角色和管理数据。然后在asp.net的MVC App中,我创建了两个模型类,如下图:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;

namespace FastFactsTestPortalMVCApp.Models
{
    public class Administrator
    {
        public int AdminId { get; set; }
        public string AdminFirstName { get; set; }
        public string AdminLastName { get; set; }
        public string AdminEmail { get; set; }
        public string AdminUserName { get; set; }
        public string AdminPassword { get; set; }
        public string AdminContactNumber { get; set; }
        public string AdminDesignation { get; set; }
        public int AdminRoleId { get; set; }
        public Nullable<System.DateTime> CreatedAt { get; set; }
        public Nullable<System.DateTime> UpdatedAt { get; set; }
        [ForeignKey("RoleId")]
        public virtual Role Role { get; set; }
    }
}

模型角色类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FastFactsTestPortalMVCApp.Models
{
    public class Role
    {
        public Role()
        {
            this.Administrators = new HashSet<Administrator>();
            this.HRs = new HashSet<HR>();
        }

        public int RoleId { get; set; }
        public string RoleName { get; set; }
        public Nullable<System.DateTime> CreatedAt { get; set; }
        public Nullable<System.DateTime> UpdatedAt { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Administrator> Administrators { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<HR> HRs { get; set; }
    }
}

然后使用管理控制器,我想注册一个用户。在这种情况下,我想创建一个视图,在其中从 linq 查询中检索角色数据并显示角色名称,以便用户可以使用角色名称进行注册。

为此,我使用了管理控制器中下面给出的创建函数:

      [AllowAnonymous]
        public ActionResult RegisterAdmin()
        {
            FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
            ViewBag.RoleId = repObj.GetRoles();
            
            return View();
           

        }

然后我编写了一个函数来保存用户的输入值:


        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SaveRegisteredAdmin(Models.Administrator userObj)
        {
             if(ModelState.IsValid)
            {
                FastFactsTestPortalRepository repObj = new FastFactsTestPortalRepository();
                
                var returnValue = repObj.AddAdmin(userObj);
                if(returnValue)
                {
                    return RedirectToAction("Login", "Home");
                }
                else
                {
                    return View("Error");
                }
              
            }
            return View("RegisterAdmin");
        }

对于注册管理员,我还创建了一个视图,其中存在错误。注册或单击提交按钮后,视图中的错误显示为 Null。空错误被称为 DropDownList。

代码如下:

@model FastFactsTestPortalMVCApp.Models.Administrator

@{
    ViewBag.Title = "RegisterAdmin";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}

<h2>RegisterAdmin</h2>

@using (Html.BeginForm("SaveRegisteredAdmin","Admin")) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Administrator</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.AdminId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminFirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminFirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminFirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminLastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminLastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminLastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminEmail, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminEmail, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminEmail, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminUserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminUserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminUserName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminPassword, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminPassword, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminPassword, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminContactNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminContactNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminContactNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminDesignation, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.AdminDesignation, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.AdminDesignation, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.AdminRoleId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.AdminRoleId, new SelectList(Model.Role.Administrators, "RoleId", "RoleName"), htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.AdminRoleId, "", new { @class = "text-danger" })


            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>


我基本上想用他/她的角色名称注册一个用户,但这是一个外键关系。因为我尝试了很多方法。我找不到正确的方法。我很想得到支持或指导来理解这个概念并纠正我的错误。

标签: c#asp.netasp.net-mvcasp.net-coreasp.net-mvc-4

解决方案


我在视图中使用以下代码纠正了错误:

 <div class="form-group">
            @Html.LabelFor(model => model.AdminRoleId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.AdminRoleId, new SelectList(ViewBag.Rolelist, "RoleId", "RoleName"), htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.AdminRoleId, "", new { @class = "text-danger" })


            </div>

推荐阅读