2017-02-27 28 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/)是專門爲此目的而設計的。 –