MVC 5 - 如何从控制器中提取 emdx 数据以查看

MVC 5 - How to pull emdx data from controller to view

MVC 新手!我可以先从我的数据库中提取数据 Entity Framework 模型 (emdx) 就好了……效果很好——有史以来最酷的东西!但是我有两个问题:

1) 我无法将数据返回到我的视图中。 (我想显示安全问题(从我的 DB First 实体数据模型 - emdx 中的存储过程返回)并允许用户回答问题。 2) 我似乎也无法重定向到不同视图文件夹中的视图(从 "View\Account" 文件夹到 "View\Home" 文件夹。

我很确定这很容易,我只是缺少一些基本的东西。

这是我的 MVC 控制器代码:

public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        string strEncr = "";
        try
        {
            if (ModelState.IsValid)
            {

                //Create Hash with Salt for For New PWs
                strEncr = Helper.ComputeHash(model.Password, "SHA512", null);
                string DBPW = "";

                string encryptedPassword = "";
                try
                {
                    using (var context = new WMSEntities1())
                    {
                         encryptedPassword = context.users
                            .Where(u => u.emailAddress == model.Username)
                            .Select(u => u.password)
                            .SingleOrDefault();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                //Test for match of PW between User and what's stored in DB
                bool flag = Helper.VerifyHash(model.Password, "SHA512", encryptedPassword);

                var loginInfo = databaseManager.LoginAndGetSecQuestion(model.Username, encryptedPassword).ToList();

                // Verification.
                if (loginInfo != null && loginInfo.Count() > 0)
                {
                    // Initialization.
                    var logindetails = loginInfo.First();

                    // Login In.
                    this.SignInUser(logindetails.emailAddress, false);
                    ViewBag.SecurityQuestion = logindetails.securityQuestion;
                    // Info.
                    return View("~/Views/Home/Index.cshtml", loginInfo);
                   // return this.RedirectToLocal(returnUrl);
                }
                else
                {
                    // Setting.
                    ModelState.AddModelError(string.Empty, "Invalid username or password.");
                }
            }
        }
        catch (Exception ex)
        {
            // Info
            Console.Write(ex);
        }

        // If we got this far, something failed, redisplay form
        return this.View(model);
    }

这是我认为的代码片段:

@*@model System.Data.DataSet*@
@model AodNetIntegration.LoginAndGetSecQuestion_Result
@{
    ViewBag.Title = "Doc Center Login Screen";
}
@*<h2>@ViewBag.Title.</h2>http://asmak9.blogspot.com/2016/03/aspnet-mvc5-integrating-existing.html
    <h3>@ViewBag.Message</h3>*@

@using (Html.BeginForm("LoginStage2", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))

{
    @Html.AntiForgeryToken()
 <table cellspacing="5" style="width: 293px;">
 <tr>
     <td></td>
     </tr>
      <tr>
     <td>
         @Html.ValidationSummary(true, "", new { @class = "text-danger" })
         @Html.LabelFor(m => m.securityQuestion, new { @class = "col-md-2 control-label, width= 50"  })
         @Html.DisplayFor(m => m.securityQuestion, new { @class = "col-md-2 control-label, width= 50" })

         @Html.ValidationMessageFor(m => m.securityQuestion, "", new { @class = "text-danger" })<br />
         @Html.LabelFor(m => m.securityQuestionAnswer, new { @class = "col-md-2 control-label" })
         @Html.PasswordFor(m => m.securityQuestionAnswer, new { @class = "form-control" })
         @Html.ValidationMessageFor(m => m.securityQuestionAnswer, "", new { @class = "text-danger" })

           </td>
          </tr>
          <tr>
            <td align="right" style="text-align: right;">

            <input type="submit" value="Submit" class="btn btn-default" />
           </td>
         </tr>
      </table>

这是我得到的错误: 当它返回到索引页面时:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[AodNetIntegration.LoginAndGetSecQuestion_Result]', but this dictionary requires a model item of type 'AodNetIntegration.LoginAndGetSecQuestion_Result'.

控制器模型方法:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace AodNetIntegration
{
   using System;

   public partial class LoginAndGetSecQuestion_Result
   {
      public int userID { get; set; }
      public string firstName { get; set; }
      public string lastName { get; set; }
      public string securityQuestion { get; set; }
      public string emailAddress { get; set; }
      public string securityQuestionAnswer { get; set; }
   }
}

谢谢,

您的查询 (var loginInfo = databaseManager....) return 是 LoginAndGetSecQuestion_Result 的集合,而不是单个对象,然后您 return 使用该集合查看视图

return View("~/Views/Home/Index.cshtml", loginInfo);

但您的视图需要单个 LoginAndGetSecQuestion_Result 对象,而不是集合。

你的代码应该是

return View("~/Views/Home/Index.cshtml", logindetails);

不过,您可以通过将查询修改为 return 单个对象并测试 null

来简化代码
var loginInfo = databaseManager.LoginAndGetSecQuestion(model.Username, encryptedPassword).FirstOrDefault();
if (loginInfo != null)
{
    this.SignInUser(loginInfo.emailAddress, false);
    ViewBag.SecurityQuestion = logindetails.securityQuestion;
    return View("~/Views/Home/Index.cshtml", loginInfo);
}
else
{
    ModelState.AddModelError(string.Empty, "Invalid username or password.");
}