65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET MVC 5:构建你的第一个 Web 应用程序 - 第四部分

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.73/5 (9投票s)

2016年8月5日

CPOL

4分钟阅读

viewsIcon

26431

downloadIcon

799

这是关于在 ASP.NET MVC 5 中构建 Web 应用程序的系列的第四部分。

引言

简单回顾一下,在 第 1 部分,我演示了如何从头开始创建一个简单的数据库,概述了 ASP.NET MVC,演示了如何使用 Entity Framework 6 构建一个简单的数据访问,以及如何在 MVC 中创建一个简单的注册页面实现。 第 2 部分 系列讨论了创建基本登录页面和在 MVC 应用程序中创建简单的基于角色的页面授权的逐步过程。 第 3 部分 系列讨论了如何使用 jQuery 和 jQuery AJAX 在应用程序中进行获取、编辑、更新和删除(FEUD)操作。

如果您还没有阅读我之前的文章,请参考以下链接

在本文中,我们将创建一个页面,允许用户修改他们的个人资料数据。

让我们开始吧!

添加 GetUserProfile() 方法

首先,打开“UserManager”类,并在下面添加以下方法

public UserProfileView GetUserProfile(int userID) {  
            UserProfileView UPV = new UserProfileView();  
            using (DemoDBEntities db = new DemoDBEntities()) {  
                var user = db.SYSUsers.Find(userID);  
                if (user != null) {  
                    UPV.SYSUserID = user.SYSUserID;  
                    UPV.LoginName = user.LoginName;  
                    UPV.Password = user.PasswordEncryptedText;  
  
                    var SUP = db.SYSUserProfiles.Find(userID);  
                    if (SUP != null) {  
                        UPV.FirstName = SUP.FirstName;  
                        UPV.LastName = SUP.LastName;  
                        UPV.Gender = SUP.Gender;  
                    }  
  
                    var SUR = db.SYSUserRoles.Find(userID);  
                    if (SUR != null) {  
                        UPV.LOOKUPRoleID = SUR.LOOKUPRoleID;  
                        UPV.RoleName = SUR.LOOKUPRole.RoleName;  
                        UPV.IsRoleActive = SUR.IsActive;  
                    }  
                }  
            }  

            return UPV;  
}  

上面的方法通过传递 SYSUserID 作为参数从数据库中获取特定的用户信息。您可能已经注意到,该方法返回 UserProfileView 类型,该类型保存了来自不同表的某些属性。 

添加 EditProfile() Action 方法

现在,打开“HomeController”类,并添加以下 action 方法

[Authorize]
public ActionResult EditProfile()
{
    string loginName = User.Identity.Name;
    UserManager UM = new UserManager();
    UserProfileView UPV = UM.GetUserProfile(UM.GetUserID(loginName));
    return View(UPV);
}


[HttpPost]
[Authorize]
public ActionResult EditProfile(UserProfileView profile)
{
    if (ModelState.IsValid)
    {
        UserManager UM = new UserManager();
        UM.UpdateUserAccount(profile);

        ViewBag.Status = "Update Sucessful!";
    }
    return View(profile);
}

上面的代码由两个 action 方法组成。第一个 EditProfile() 方法将在请求页面并将其加载到浏览器后被调用。它所做的是通过传递 SYSUserID 作为参数来调用 GetUserProfile() 方法来获取用户个人资料数据。第二个是重载方法,将在 POST 请求期间被调用,也就是说,当你点击 Button 保存数据时。它所做的是首先检查字段的有效性(它们是否有效且不为空),然后调用方法 UpdateUserAccount(),并将 View 中的 UserProfileView 模型传递给该方法。如果您还记得我之前的系列文章,UpdateUserAccount() 方法是执行将数据实际保存到我们数据库的地方。

您可能还注意到,两个 action 方法都用 [Authorize] 属性装饰,以确保两个方法都只能被经过身份验证的用户访问,无论角色如何。

添加 EditProfile View

下一步是为个人资料页面生成 View。为此,右键单击 EditProfile() 方法,然后选择“添加视图”。在“添加视图”对话框中,提供所需的字段,如下图所示

图 1:添加视图对话框

注意 Model 类字段的值。它应该是“UserProfileView”。现在,单击“添加”为您搭建 UI。

Visual Studio 将根据您在 ModelUserProfileView)中定义的字段,在 View 中生成所有控件。这意味着它还会生成我们不想编辑的不必要的字段,例如 LOOKUPRoleIDIsRoleActive。除此之外,我们还需要提供一个下拉列表来显示 Gender 字段。因此,请务必更新生成的 HTML 标记。它看起来应该类似于以下内容

@model MVC5RealWorld.Models.ViewModel.UserProfileView  
  
@{  
    ViewBag.Title = "EditProfile";  
    Layout = "~/Views/Shared/_Layout.cshtml";  
}  
  
<h2>Edit Your Profile</h2>  
  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
        <hr />  
        <span class="alert-success">@ViewBag.Status</span>  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        @Html.HiddenFor(model => model.SYSUserID)  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.RoleName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.DisplayFor(model => model.RoleName)  
                @Html.ValidationMessageFor(model => model.RoleName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.LoginName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.LoginName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.LoginName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.DropDownListFor(model => model.Gender, new List<SelectListItem> {  
                    new SelectListItem { Text="Male", Value="M" },  
                    new SelectListItem { Text="Female", Value="F" }  
                }, new { @class = "form-control" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Save" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
  
<div>  
    @Html.ActionLink("Back", "Welcome")  
</div>

上面的标记是一个强类型 View,它基于 UserProfileView 模型渲染 HTML。现在,在“Welcome.cshtml”视图中添加以下标记。

@Html.ActionLink("Edit Profile", "EditProfile", "Home")

上面的标记只不过是到 EditProfile 页面的链接,因此当您登录时,您可以轻松地导航到您的个人资料页面并开始修改数据。

测试应用程序

现在,尝试构建您的代码并运行您的应用程序。输出应该类似于下图

图 2:编辑用户页面

修改数据后

图 3:成功更新后

就这样!我希望有人觉得这篇文章有用。如果您想测试您的 MVC 5 应用程序在 IIS 上运行,您可以参考这篇关于以下内容的逐步文章:将您的 ASP.NET MVC 5 应用程序部署到 IIS8

摘要

在这个系列中,我们没有看到很多功能,但我们已经学会了创建一个非常基本的个人资料页面,让用户可以在 MVC 5 应用程序中修改他们的信息。

© . All rights reserved.