【问题标题】:MVC 5 - How to pull emdx data from controller to viewMVC 5 - 如何从控制器中提取 emdx 数据以查看
【发布时间】:2016-10-16 06:23:35
【问题描述】:

MVC 新手!我可以从我的数据库第一个实体框架模型(emdx)中提取数据就好了……效果很好 - 有史以来最酷的东西!但我有两个问题:

1) 我无法将数据返回到我的视图中。 (我想显示安全问题(从我的 DB First Entity Data Model - 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; }
   }
}

谢谢,

【问题讨论】:

  • 您有名为SecurityQuestions 的视图吗?您需要添加更多代码以了解您要执行的操作(包括该控制器方法的签名和该视图的名称)。你的代码中没有任何地方重定向
  • 谢谢 - 我做了一些编辑...我只是想出了如何重定向到不同文件夹中的正确视图(我之前尝试过这个,但有一个错字)现在我得到了错误在帖子中...我现在将发布更多代码
  • @StephenMuecke - 够了吗?非常感谢!!
  • 当你应该返回 logindetails 时返回 loginInfo(这是你的收藏)(返回 View("~/Views/Home/Index.cshtml", logindetails);` 但是 @987654328 @ 可以是 null 所以这里没有理由测试它,你的代码应该是 LoginAndGetSecQuestion_Result logindetails = databaseManager.LoginAndGetSecQuestion(model.Username, encryptedPassword).FirstOrDefault(); if (logindetails == null) { // error } else { // return view };
  • 但不清楚为什么您使用return View(..) 而不是重定向到显示您显示的视图的方法。

标签: entity-framework asp.net-mvc-5 model-view


【解决方案1】:

您的查询 (var loginInfo = databaseManager....) 正在返回 LoginAndGetSecQuestion_Result 的集合,而不是单个对象,然后您使用该集合将该集合返回到视图

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

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

你的代码应该是

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

但是,您可以通过修改查询以返回单个对象并测试 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.");
}

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    相关资源
    最近更新 更多