保存数据时MVC两类在一个模型冲突中

时间:2017-02-27 08:49:59

标签: asp.net-mvc asp.net-mvc-5

我的代码如下所示

MODEL

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);
        }

查看

@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: 'bg-@ViewBag.Type' //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.

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

这可能适用于这样的两个类吗?

帮帮我,我被困在这里。

1 个答案:

答案 0 :(得分:0)

您的UserMaster类具有CPassword属性,当您执行db.UserMasters.SingleOrDefault(x => x.UserID == uid)时,该属性将设置为null。您更新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&lt; =&gt;你控制器方法中的viewModel映射。