【问题标题】:Use and ArrayList to display data from an MVC Controller to a Razor Page使用和 ArrayList 将数据从 MVC 控制器显示到 Razor 页面
【发布时间】:2022-06-11 02:48:57
【问题描述】:

我对使用数组列表非常陌生,并且想了解如何将数据从控制器中显示数据,该控制器的方法中有一个数组到 MVC Razor 页面。我正在创建一个运行良好的登录名,但希望将捕获的数据从 Active Directory 显示到 UserLoginData.CSHTML 页面。我读到最好的方法是通过模型。任何帮助将不胜感激! (我只想要 Razor 数据页面上的表中的 ArrayList。)

控制器:

在此处输入代码

           public ActionResult UserLoginData(string username, string LblUserName, string 
    UserName, ArrayList AuthorizationGroups)
    {
        UserLoginModel model = new UserLoginModel();
        UserName = username;
        ViewBag.UserName = UserName;
        model.UserName = UserName;
        model.LblUserName = model.UserName;
        model.AuthorizationGroups = AuthorizationGroups;

        foreach (var item in AuthorizationGroups)
        {
             // Console.WriteLine(item);
            model.item = item;
        
        }
      
        
        
        return View(model);
    }

模型(属性):

   //Labels for UserLoginData:

public string LblUserName { get; set; }
public string LblTitle { get; set; }
public string LblPlantLocation { get; set; }
public string LblUserLoggedInTimeStamp { get; set; }
public string LblUserLoggedOutTimeStamp { get; set; }
public string LblDisplayName { get; set; }
public string LblEmail { get; set; }

    
    //For the ArrayList of MemberGroups. 
    public ArrayList AuthorizationGroups { get; set; }
    public ArrayList YardDogUserGroupMembers { get; set; }
    public ArrayList MemberOfUserGroups { get; set; }
    public ArrayList YardDogAdminGroupMembers { get; set; }
    
    public object item { get; set; }

剃刀 CSHTML:

在此处输入代码

@model PW_Login.Models.UserLoginModel
@{
Layout = null;
/*
WebGrid webGrid = new WebGrid(source: Model, canPage: true, canSort: true, 
sortDirectionFieldName: "PlantLocation", rowsPerPage: 50);
webGrid.Pager(WebGridPagerModes.All);
*/

 }

 <!DOCTYPE html>

<html>

<head>
<link href="~/Content/UserLogin.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
</head>
<body>

@using (Html.BeginForm("UserLoginData", "LoginController", FormMethod.Post, new { id = 
"LoginDataForm", Class = "LoginDataForm" }))
{
    //Html.ListBoxFor(model=>model.AuthorizationGroups, Model.AuthorizationGroups)
    // string UserName = Session["UserName"].ToString();
    <label></label>
    //Html.LabelFor(model => model.UserName, @Model.UserName)

    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.UserName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UserPlantLocation)
            </th>
        </tr>
            <tr>
                <td>
                    <!--- Html.DisplayFor(modelItem => item.AuthorizationGroups) -->
                    @foreach ( var item in Model.AuthorizationGroups)
            {
                        @Html.DisplayNameFor(Modelitem=>item)
            }
                </td>
             
            </tr>
        
    </table>

}

</body>

</html>

Controller中从AD获取信息的方法:

        private void ShowUserInformation(SearchResult rs, string UserName)
    {
        UserLoginModel model = new UserLoginModel();
        Cursor.Current = Cursors.Default;
        model.UserName = UserName;
        Session["UserName"] = UserName;
        Session["LblUserName"] = UserName;

        DateTime now = DateTime.Now;
        string UserLoggedInTimeStamp = now.ToString();

        model.LblUserLoggedInTimeStamp = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");

        //Push the UserName into the Label via the model.
        if (rs.GetDirectoryEntry().Properties["samaccountname"].Value != null)
            model.LblUserName = "Username : " + 
        rs.GetDirectoryEntry().Properties["samaccountname"].Value.ToString();

        if (rs.GetDirectoryEntry().Properties["title"].Value != null)
            model.LblTitle = "Title : " + 
        rs.GetDirectoryEntry().Properties["title"].Value.ToString();

        //description returns null... need to find out active directory folder/subfolder. 
        if (rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value != null) 
       //PhysicalDeliveryOfficeName returns 110.
            model.LblPlantLocation = "PlantLocation : " + 
       rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString();
        
        if (rs.GetDirectoryEntry().Properties["member"].Value != null)
            model.LblMemberGroup = "Member : " + 
       rs.GetDirectoryEntry().Properties["member"].Value.ToString();
        
        //DisplayName or DistinguishedName is what I do believe is in the security group 
       "YardDogUser" or "YardDogAdmin".
        if (rs.GetDirectoryEntry().Properties["distinguishedName"].Value != null)
            model.LblDistinguishedName = "distinguishedName : " + 
        rs.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString();
        //NULL... 
        if (rs.GetDirectoryEntry().Properties["YardDogAdmin"].Value != null)
            model.LblYardDogAdmin = "YardDogAdmin : " + 
        rs.GetDirectoryEntry().Properties["YardDogAdmin"].Value.ToString();

        if (rs.GetDirectoryEntry().Properties["displayname"].Value != null)
            model.LblDisplayName = "Display Name : " + 
        rs.GetDirectoryEntry().Properties["displayname"].Value.ToString();

        if (rs.GetDirectoryEntry().Properties["email"].Value != null)
            model.lblEmail = "Email Address : " + 
        rs.GetDirectoryEntry().Properties["email"].Value.ToString();

       
        /*
          //Member Of Office 365 Groups. Use if needed!
           ///ArrayList MemberOfGroups = new ArrayList();
          var MemberOfGroups = new ArrayList();  //perfered way of writing. 
          string Ret1 = string.Empty;
          foreach (object memberOf in rs.GetDirectoryEntry().Properties["memberOf"])
          {
              MemberOfGroups.Add(Ret1 += " Member Of : " + memberOf.ToString() + "\n");
          }
                */

        //Get Security Groups that User belongs to. Note: Doesn't show other groups (won't 
        show YardDogAdmin). 
        ArrayList SecurityGroups = new ArrayList();

        foreach (IdentityReference group in 
        System.Web.HttpContext.Current.Request.LogonUserIdentity.Groups)
        {
            SecurityGroups.Add(group.Translate(typeof(NTAccount)).ToString());
        }

        //model doesn't show the correct datetime on these. 
        model.LblUserLoggedInTimeStamp = model.UserLoggedInTimeStamp.ToString();
        model.LblUserLoggedOutTimeStamp = model.UserLoggedOutTimeStamp.ToString();

        /******************************************************************************/


        //Search to see if this group exists that starts with "YardDog". 
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
        {

            ArrayList FoundYardDogAdmin = new ArrayList();
            ArrayList SecurityGroupsFound = new ArrayList();
            // define a "query-by-example" principal - here, we search for a GroupPrincipal 
            // and with the name like some pattern
            GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
            qbeGroup.Name = "YardDog*"; //Find all the User Groups for this User that is 
        logging in. 

            // create your principal searcher passing in the QBE principal    
            PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
            string Ret4 = string.Empty;
            // find all matches
            foreach (var found in srch.FindAll())
            {
                FoundYardDogAdmin.Add(Ret4 += " GroupFound : " + found.ToString() + "\n");
                SecurityGroupsFound.Add(Ret4 += " GroupFound : " + qbeGroup.ToString() + 
      "\n");
            }
            //Count where the User's Display Name exists is needed next. We could do this here 
       or when we get all the Groups. 
        }

        //Search for all User's of YardDogAdmin Group and list them in the ArrayList. 
        /*
        using PrincipalContext ctxDomain = new PrincipalContext(ContextType.Domain);
        {

            // get the group you're interested in
            GroupPrincipal GroupMembers = GroupPrincipal.FindByIdentity("YardDogAdmin");

            ArrayList GroupMembersArray = new ArrayList();

            // iterate over its members
            foreach (Principal principal in GroupMembers.Members)
            {
                GroupMembersArray.Add(principal);
            }
        }
        */
        /* Below works, finds all in YardDogAdmin's, YardDogUser's (Finds security groups by 
        string search). Use if needed.*/
        using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
        {
            //Groups to validate against for current User. 
           var GroupYardDogAdminPrincipalName = "YardDogAdmin";
            var GroupYardDogUserPrincipalName = "YardDogUser";
            //Find the current User's Groups. 
            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, UserName);
            //Find all User's within these Groups. 
            GroupPrincipal YardDogAdminMembers = GroupPrincipal.FindByIdentity(ctx, 
     GroupYardDogAdminPrincipalName);
            GroupPrincipal YardDogUserMembers = GroupPrincipal.FindByIdentity(ctx, 
     GroupYardDogUserPrincipalName);
         
            //UserGroups that the User logged in belongs to. 
            if (user != null)
            {
                var MemberOfUserGroups = new ArrayList();
                model.MemberOfUserGroups = MemberOfUserGroups;
                var groups = user.GetAuthorizationGroups();
                
                foreach (GroupPrincipal group in groups)
                {
                    MemberOfUserGroups.Add(group);
                }
                
                if (MemberOfUserGroups.Contains("YardDogAdmin"))
                {
      //Pass to the model YardDogAdmin exists for this user (AdminFlag translates to 
     LocationData table).
                    model.LblYardDogAdmin = "Y";
                    model.AdminFlag = "Y";

                }
                else
                {
                    model.LblYardDogAdmin = "N";
                    model.AdminFlag = "N";
                }

                //Get the Members of YardDogAdmin and their warehouse locations. 
                if (YardDogAdminMembers != null)
                {
                    var YardDogAdminGroupMembers = new ArrayList();
                    model.YardDogAdminGroupMembers = YardDogAdminGroupMembers;
                    foreach (Principal principal in YardDogAdminMembers.Members)
                    {
                     rs = SearchUserByDisplayName(principal.DisplayName.ToString());
                       YardDogAdminGroupMembers.Add(principal.DisplayName + " " + 
                         
    rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString() + " 
           YardDogAdmin");
                    }
                }
                //Get the Members of YardDogUser and their location.
                if (YardDogUserMembers != null)
                {
                    var YardDogUserGroupMembers = new ArrayList();
                    model.YardDogUserGroupMembers = YardDogUserGroupMembers;
                    foreach (Principal principal in YardDogUserMembers.Members)
                    {
                        rs = SearchUserByDisplayName(principal.DisplayName.ToString());
                          YardDogUserGroupMembers.Add(principal.DisplayName + " " +
                            
      rs.GetDirectoryEntry().Properties["physicaldeliveryofficename"].Value.ToString() + " 
      YardDogUser");
                    }
                }
            }
        }

【问题讨论】:

  • 看,这就是为什么我强烈支持删除这些遗留类,如ArrayList。让这些人的代码不再编译,清理一下框架。我的意思是这个人似乎特别从rs.GetDirectoryEntry() 获得报酬,想象一下他正确地重写他的代码会得到多少报酬。
  • 其中一些目录条目是嵌入了其他信息的对象。那么在重写这个时会有什么建议呢?......我愿意接受改进的想法。 ArrayList 速度很快,我决定使用那个时间的引用来获取数据。

标签: arraylist model-view-controller razor


【解决方案1】:

只需在控制器中创建 TempData[] 从一个控制器动作结果到另一个控制器动作结果,然后也进入模型。之后,您可以访问 TempData 并根据该会话的需要保留它。只需遍历 TempData 中的对象以显示在标签中。

enter code here

@model PW_Login.Models.UserLoginModel
 @{
Layout = null;

string UserName = TempData["UserName"].ToString();
string PlantLocation = TempData["UserPlantLocation"].ToString();
string UserLoggedInTimeStamp = 
 TempData["UserLoggedInTimeStamp"].ToString();

//Get the TempData Sessions and write them out. 
var SecurityGroups = TempData["SecurityGroups"];
var MemberOfUserGroups = TempData["MemberOfUserGroups"];
var YardDogAdminGroupMembers = TempData["YardDogAdminGroupMembers"];
var YardDogUserGroupMembers = TempData["YardDogUserGroupMembers"];

TempData.Keep(UserLoggedInTimeStamp.ToString());
TempData.Keep(SecurityGroups.ToString());
TempData.Keep(MemberOfUserGroups.ToString());
TempData.Keep(YardDogAdminGroupMembers.ToString());
TempData.Keep(YardDogUserGroupMembers.ToString());


// PW_Login.Models.UserLoginModel LoginModel;

// LoginModel.SecurityGroups = SecurityGroups;

 }

 <!DOCTYPE html>

 <html>

<head>
<link href="~/Content/UserLogin.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
 </head>
 <body>
<asp:Panel runat="server" ID="Panel2" HorizontalAlign="Center">
    <img id="PM_Logo" src="~/images/PremiumWatersLogo.PNG" />
</asp:Panel>

<h2>User Login Groups</h2><br /><br />
<div id="time"></div>
<SCRIPT LANGUAGE="Javascript">

    function checkTime(i) {
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        }
        function startTime() {
            var today = new Date();
            var h = today.getHours();
            var m = today.getMinutes();
            var s = today.getSeconds();

            // add a zero in front of numbers<10
            m = checkTime(m);
            s = checkTime(s);
            document.getElementById('time').innerHTML = h + ":" + m + ":" + 
  s; //Get the time.
            document.getElementById('time').innerHTML = "Date: " + today; 
 //Get the Date.
            t = setTimeout(function () {
                startTime()
            }, 500);
        }
        startTime();
</SCRIPT>
@using (Html.BeginForm("UserLoginData", "LoginController", FormMethod.Post, 
  new { id = "LoginDataForm", Class = "LoginDataForm" }))
{

    <dv id="FlexLoginDataTables" class="FlexLoginDataTables">
        <table id="LoginDataTable" class="LoginDataTable">
            <tr>
                <th>
                    @Html.LabelForModel(UserName, "User Name: ")
                </th>
            </tr>
            <tr>
                <td>
                    @foreach (var group in @Model.SecurityGroups)
                    {
                        <label id="LoginDataLabel" 
     class="LoginDataLabel">@group.ToString()</label><br />
                    }
                </td>
            </tr>
        </table>
        <table id="LoginDataTable" class="LoginDataTable">
            <tr>
                <th>
                    @Html.LabelFor(m => m.YardDogAdminGroupMembers)
                </th>
            </tr>
            <tr>
                <td>
                    @foreach (var group in @Model.YardDogAdminGroupMembers)
                    {
                        <label id="LoginDataLabel" 
     class="LoginDataLabel">@group.ToString()</label><br />
                    }
                </td>
            </tr>

        </table>
        <table id="LoginDataTable" class="LoginDataTable">
            <tr>
                <th>
                    @Html.LabelFor(m => m.YardDogUserGroupMembers)
                </th>
            </tr>
            <tr>
                <td>
                    @foreach (var group in @Model.YardDogUserGroupMembers)
                    {
                        <label id="LoginDataLabel" 
    class="LoginDataLabel">@group.ToString()</label><br />
                    }
                </td>
            </tr>
        </table>
    </dv>
    <table>
        <tr>
            <th>
                @Html.LabelFor(model => model.UserLoggedInTimeStamp, 
     @Model.UserLoggedInTimeStamp)
            </th>
            <td>
                @Html.Label(@Model.UserLoggedInTimeStamp.ToString())
            </td>
        </tr>
    </table>
    <table id="LoginDataTable" class="LoginDataTable">
        <tr>
            <th>
            </th>
            <td>
            </td>
        </tr>
    </table>

}

 </body>

 </html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多