2017-02-27 151 views
0

是如下图所示MVC两个类在保存数据

模型

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.ComponentModel.DataAnnotations.Schema; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
namespace MyProject.Models 
{ 
    [Table("UserMaster")] 
    public partial class UserMaster 
    { 
    [Key] 
    public int UserID { get; set; } 
    [System.Web.Mvc.Remote("doesAlreadyExist", "User", HttpMethod = "POST", ErrorMessage = "User Number already exists. Please enter a different Number.")] 
    [Required(ErrorMessage = "Enter Personal No")] 
    [Display(Name = "User No")] 
    [StringLength(10)] 
    public string User No{ get; set; } 

    [Required(ErrorMessage = "Enter Password")] 
    [Display(Name = "Password")] 
    public string Password { get; set; } 

    [NotMapped] 
    [Compare("Password", ErrorMessage = "Password doesn't match.")] 
    [Display(Name = "Confirm Password")] 
    public string CPassword { get; set; } 
} 


public class UserChangePassMV 
    { 
     [Required] 
     [Display(Name = "Old Password")] 
     [DataType(DataType.Password)] 
     public string OldPassword { get; set; } 

     [Required] 
     [Display(Name = "New Password")] 
     [DataType(DataType.Password)] 
     public string NewPassword { get; set; } 

     [NotMapped] 
     [Display(Name = "Confirm Password")] 
     [DataType(DataType.Password)] 
     [Compare("NewPassword",ErrorMessage="Password Doesnt Match in User Change Password.")] 

     public string ConfirmPassword { get; set; } 
    } 
public class ChangeAvatar 
    { 
     public byte[] Photo { get; set; } 

     public string ImgSrc { get; set; } 
    } 
} 

电脑板我的代码(一个)模型冲突

[OutputCache(Duration = 10, VaryByParam = "none", Location = OutputCacheLocation.Client, NoStore = true)] 
     public ActionResult ChangeAvatar() 
     { 
      ChangeAvatar avatar = new Models.ChangeAvatar(); 
      int uid = Convert.ToInt32(Session.GetDataFromSession<CommonUserSession>("CommonUserSession").UserID); 
      avatar.Photo = db.UserMasters.SingleOrDefault(x => x.UserID == uid).Photo; 

      if (avatar.Photo != null) 
      { 
       string imageBase64 = Convert.ToBase64String(avatar.Photo); 
       avatar.ImgSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64); 
      } 
      return View("ChangeAvatar", "_Layout", avatar); 
     } 

     [HttpPost] 
     public ActionResult ChangeAvatar(HttpPostedFileBase file) 
     { 
      if (file == null) 
      { 
       ModelState.AddModelError("", "Select image to upload"); 
      } 

      int uid = Convert.ToInt32(Session.GetDataFromSession<CommonUserSession>("CommonUserSession").UserID); 
      UserMaster Mem = db.UserMasters.SingleOrDefault(x => x.UserID == uid); 
      try 
      { 
       if (ModelState.IsValid) 
       { 
        string path = System.IO.Path.Combine(Server.MapPath("~/ProfileImg"), uid.ToString() + ".jpg"); 
        // file is uploaded 
        file.SaveAs(path); 

        using (MemoryStream ms = new MemoryStream()) 
        { 
         file.InputStream.CopyTo(ms); 
         byte[] array = ms.GetBuffer(); 
         Mem.Photo = array; 
        } 
        db.SaveChanges(); 
        return RedirectToAction("ChangeAvatar"); 
       } 
      } 
      catch (DbEntityValidationException ex) 
      { 
       var errorMessages = ex.EntityValidationErrors 
         .SelectMany(x => x.ValidationErrors) 
         .Select(x => x.ErrorMessage); 


       var fullErrorMessage = string.Join("; ", errorMessages); 

       var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); 
       HtmlHelperExtensions.LogError(ex); 
       throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); 

      } 
      catch (RetryLimitExceededException /* dex */) 
      { 
       ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator."); 
      } 

      ChangeAvatar avatar = new Models.ChangeAvatar(); 
      avatar.Photo = db.UserMasters.SingleOrDefault(x => x.UserID == uid).Photo; 

      if (avatar.Photo != null) 
      { 
       string imageBase64 = Convert.ToBase64String(avatar.Photo); 
       avatar.ImgSrc = string.Format("data:image/jpeg;base64,{0}", imageBase64); 
      } 
      return View(avatar); 
     } 

VIEW

@model MyProject.Models.ChangeAvatar 
@{ 
    ViewBag.Title = "Change Avatar"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 
<!-- BEGIN PAGE BAR --> 
@section PageBreadcrumb{ 
    <ul class="breadcrumb"> 
     <li><a href="~/Home/Index"><i class="icon-home2 position-left"></i> Dashboard</a></li> 
     <li class="active">Change Avatar</li> 
    </ul> 
} 
<!-- END PAGE BAR --> 
<div class="clearfix"></div> 
@section PageJS{ 
    <script type="text/javascript" src="~/assets/js/plugins/uploaders/fileinput.min.js"></script> 
    <script type="text/javascript" src="~/assets/js/pages/uploader_bootstrap.js"></script> 
    <script type="text/javascript"> 
     if ('@ViewBag.Status' != "") { 
      var notice = new PNotify({ 
       title: '@ViewBag.Status', 
       text: '@ViewBag.Msg', 
       addclass: '[email protected]' //primary,info,danger,success,warning 
      }).get().click(function() { 
       notice.remove(); //Click to remove 
      }); 

     } 
    </script> 
} 

@using (Html.BeginForm("ChangeAvatar", "User", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary() 
    <div class="panel panel-flat"> 
     <div class="panel-heading"> 
      <h5 class="panel-title text-primary">Change Avatar</h5> 
      <div class="heading-elements"> 
       <ul class="icons-list"> 
        <li><a data-action="collapse"></a></li> 
        @*<li><a data-action="reload"></a></li> 
         <li><a data-action="close"></a></li>*@ 
       </ul> 
      </div> 
     </div> 
     <div class="panel-body"> 
      <div class="col-md-12"> 

       <div class="form-group"> 
        <label class="col-lg-2 control-label text-semibold">Avatar:</label> 
        <div class="col-lg-10"> 
         <input type="file" name="file" class="file-input-custom" data-show-caption="true" data-show-upload="true" accept="image/*"> 
         <span class="help-block">Show only image files for selection &amp; preview.</span> 
        </div> 
       </div> 

       <div class="col-lg-12"> 
        <div class="text-right"> 
         <p> 
          <div class="text-right"> 
           @*<button type="submit" class="btn btn-primary">Change <i class="icon-arrow-right14 position-right"></i></button>*@ 
          </div> 
         </p> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
} 

现在,当我试图保存更改头像的数据就说明第一个模型的误差

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: Password doesn't match. 

如果我删除比较部分比它的工作原理,但我需要的是比较确认密码

是否可以像这样使用两个类?

帮帮我我卡在这里。

+0

似乎使用'ModelState.IsValid'在那里触发'DbEntityValidationException'的验证检查,因为由于验证约束的应用,UserMaster' viewmodel的使用是可疑的:'UserMaster Mem = db.UserMasters.SingleOrDefault(x => x.UserID == uid);' –

+0

我已经使用 '@model MyProject.Models.ChangeAvatar' 在视图中 –

+0

您是否可以粘贴您的视图代码?你有你的客户端验证启用? –

回答

0

您的UserMaster类有一个CPassword属性,当您执行db.UserMasters.SingleOrDefault(x => x.UserID == uid)时,该属性将设置为空。您更新Photo字段并保存该实体。 db.SaveChanges();在您的实体上触发验证,该实体正在比较产生异常的密码字段值。 MVC和EF都使用数据注释属性进行验证。 EF读取为表示层设计的属性。

想一想你为什么需要在模型类中使用CPassword字段?它不存储在数据库中。仅需要捕获用户输入。通常这就是所谓的viewModel职责。为了解决这个问题,拆分UserMaster到单独的类。

public partial class UserMaster 
{ 
    [Key] 
    public int UserID { get; set; } 

    [Required] 
    [Display] 
    [StringLength(10)] 
    public string UserNo { get; set; } 

    [Required] 
    public string Password { get; set; } 
} 

public class UserMasterViewModel 
{ 
    public int UserID { get; set; } 

    [System.Web.Mvc.Remote("doesAlreadyExist", "User", HttpMethod = "POST", ErrorMessage = "User Number already exists. Please enter a different Number.")] 
    [Required(ErrorMessage = "Enter Personal No")] 
    [Display(Name = "User No")] 
    [StringLength(10)] 
    public string UserNo{ get; set; } 

    [Required(ErrorMessage = "Enter Password")] 
    [Display(Name = "Password")] 
    public string Password { get; set; } 

    [Compare("Password", ErrorMessage = "Password doesn't match.")] 
    [Display(Name = "Confirm Password")] 
    public string CPassword { get; set; } 
} 

使用UserMasterViewModel作为您的意见的@model。在你的控制器方法中执行dbModel < => viewModel映射。

+0

我学到了新的东西,谢谢 –

+0

是否有任何简单的方法映射因为我在主模型中有超过50个字段。 https://www.codeproject。com/Articles/1043977/Mapping-ViewModel-to-Model-in-ASP-NET-MVC-using-Im 我正在参考。从上面链接。 –

+0

@Ravi Mehta嗯,确实如此。 [Automapper](http://automapper.org/)是专门为此目的而设计的。 –