更新少数更改字段MVC 3项目

时间:2013-10-07 05:21:42

标签: c# asp.net-mvc entity-framework

我创建了一个MVC 3网站,允许用户在线注册和购买东西。我正在使用EF进行所有数据库操作。我对用户类的实现如下

public class User
{
    [HiddenInput(DisplayValue = false)]
    public long UserID { get; set; }

    [Required(ErrorMessage = "Please enter a first name")]
    [Display(Name="First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Please enter a last name")]
    [Display(Name="Last Name")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Please enter an Email")]
    [RegularExpression(".+\\@.+\\..+", ErrorMessage="Please enter a valid email")]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Please enter a phone number")]
    [Display(Name = "Phone Number")]
    public string PhoneNumber { get; set; }

    [Required(ErrorMessage = "Please enter a value for address line 1")]
    [Display(Name = "Address Line 1")]
    public string AddressLine1 { get; set; }

    [Required(ErrorMessage = "Please enter a value for address line 2")]
    [Display(Name = "Address Line 2")]
    public string AddressLine2 { get; set; }

    [Required(ErrorMessage = "Please enter a city")]
    [Display(Name = "City")]
    public string City { get; set; }

    [Required(ErrorMessage = "Please enter a country")]
    [Display(Name = "Country")]
    public string Country { get; set; }

    [Required(ErrorMessage = "Please enter a login name")]
    [Display(Name = "Your Login Name")]
    public string UserName { get; set; }

    [Required(ErrorMessage = "Please enter a password")]
    [DataType(DataType.Password)]
    [Compare("Password")]
    [Display(Name = "Your Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Compare("Password", ErrorMessage="Passwords do not match")]
    [System.ComponentModel.DataAnnotations.Schema.NotMapped]
    [Display(Name = "Confirm Password")]
    public string ConfirmPassword { get; set; }
}

现在我遇到的问题是在更新用户详细信息时。我希望我会提供两个不同的页面来更新细节。一个用于更改密码,另一个用于更改其他详细信息。但是,问题是当我创建一个视图以启用其他详细信息的编辑,密码激活的验证并且不允许我保存数据。我希望未显示的字段数据与存储在数据库中的数据相同。

请帮助我,因为这是我在这里的第一个问题,请告诉我你需要解决我的问题的其他任何事情。以下是用户控制器编辑操作的代码:

 public ViewResult Edit(int userId)
    {
        User user = repository.Users.Where(x => x.UserID == userId).Select(x => x).FirstOrDefault();
        user.UserName = repository.Users.Where(x => x.UserID == userId).Select(x => x.UserName).FirstOrDefault();
        return View(user);
    }

    [HttpPost]
    public ActionResult Edit(User user)
    {
        //user.Password = repository.Users.Where(u => u.UserName.Equals(user.UserName)).Select(p => p.Password).FirstOrDefault().ToString();
        user.ConfirmPassword = user.Password;

        if (ModelState.IsValid)
        {
            repository.AddUser(user, "Edit");
            TempData["message"] = string.Format("{0} has been saved", (user.FirstName+ " " +user.LastName));
            return RedirectToAction("ListUsers", "User");
        }
        else
        {
            return View(user);
        }
    }

以下是用于编辑用户的视图的代码

@model SportsStore.Domain.Entities.User

@{
    ViewBag.Title = "Edit User";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

<h2>Edit @Model.FirstName @Model.LastName</h2>

@Html.ValidationSummary()

@using (Html.BeginForm("Edit", "User", FormMethod.Post))
{

<table class="Grid">
    <tr>
        <td>First Name</td>
        <td>@Html.EditorFor(x => x.FirstName)</td>
    </tr>
    <tr>
        <td>Last Name</td>
        <td>@Html.EditorFor(x => x.LastName)</td>
    </tr>
    <tr>
        <td>Email</td>
        <td>@Html.EditorFor(x => x.Email)</td>
    </tr>
    <tr>
        <td>Phone Number</td>
        <td>@Html.EditorFor(x => x.PhoneNumber)</td>
    </tr>
    <tr>
        <td>Address Line 1</td>
        <td>@Html.EditorFor(x => x.AddressLine1)</td>
    </tr>
    <tr>
        <td>Address Line 2</td>
        <td>@Html.EditorFor(x => x.AddressLine2)</td>
    </tr>
    <tr>
        <td>City</td>
        <td>@Html.EditorFor(x => x.City)</td>
    </tr>
    <tr>
        <td>Country</td>
        <td>@Html.EditorFor(x => x.Country)</td>
    </tr>
</table>
@*Html.EditorFor(x => x.UserName)
@Html.PasswordFor(x => x.Password)
@Html.HiddenFor(x => x.ConfirmPassword)

@*{Model.ConfirmPassword = Model.Password;}*@

<input type="submit" value="Save" />
if (User.Identity.Name.Equals("admin", StringComparison.OrdinalIgnoreCase))
{
    @Html.ActionLink("Cancel and return to User List", "ListUsers");
}
else
{
    @Html.ActionLink("Cancel and return to User List", "List", "Product");
}
}

1 个答案:

答案 0 :(得分:2)

您应将其拆分为ViewModels,其中一个包含用户登录信息UserLoginViewModelUserInfoViewModel,其中仅包含其他用户信息。只需在每个模型中添加更新所需的属性,例如下面的UserLoginModelo

public class UserLoginViewModel
{
  [HiddenInput(DisplayValue = false)]
  public long UserID { get; set; }

  [Required(ErrorMessage = "Please enter a password")]
  [DataType(DataType.Password)]
  [Compare("Password")]
  [Display(Name = "Your Password")]
  public string Password { get; set; }

  [DataType(DataType.Password)]
  [Compare("Password", ErrorMessage="Passwords do not match")]
  [System.ComponentModel.DataAnnotations.Schema.NotMapped]
  [Display(Name = "Confirm Password")]
  public string ConfirmPassword { get; set; }
}

然后,基于此模型创建强类型视图。控制器应该期望每个视图模型,然后您可以将每个atributte映射到真实的User对象,然后保存所有更改:

查看:

@model SportsStore.Domain.Entities.UserLoginViewModel 

控制器:

[HttpPost]
public ActionResult Edit(UserLoginViewModel user)
{
   //Retrieve the user and map every updated property to the original User
}

[HttpPost]
public ActionResult Edit(UserInfoViewModel user)
{
   //Retrieve the user and map every updated property to the original user
}