MVC5保存更新的数据错误总是需要上传新文件

时间:2018-05-06 08:19:36

标签: c# asp.net-mvc

我在编辑回数据库后尝试保存数据。问题在于文件上传。我每次想要保存编辑数据时都要上传新图像,否则控制器会认为我的img属性为null。所以我将我的编辑操作重写为喜欢这样,希望它能使用我上传的图像

[HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit([Bind(Include = "id,name,info,whatThisTeach,whatToKnow")] Major major, HttpPostedFileBase img)
        {

            if (ModelState.IsValid)
            {
                if(img != null)
                {
                    major.img = new byte[img.ContentLength];
                    img.InputStream.Read(major.img, 0, img.ContentLength);
                }
                else
                {
                    var m = db.Majors.Find(major.id);
                    major.img = m.img;              
                }
                db.Entry(major).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View("Details", major);
        }

但是当我尝试编辑数据而不上传新图片时,它给了我这个错误:

  

System.InvalidOperationException HResult = 0x80131509
  消息=附加类型' MUC.Models.Major'的实体。失败是因为   另一个相同类型的实体已经拥有相同的主键   值。使用'附加'方法或设置   一个实体的状态为“未变”'或者'修改'如果有任何实体   图表具有冲突的键值。这可能是因为某些实体   是新的,尚未收到数据库生成的键值。在   这种情况使用'添加'方法或“添加”#39;实体状态跟踪   图表然后将非新实体的状态设置为“未更改”。要么   '变形'作为适当的。 Source = EntityFramework StackTrace:
  在   System.Data.Entity.Core.Objects.ObjectContext.VerifyRootForAdd(布尔   doAttach,String entitySetName,IEntityWrapper wrappedEntity,   EntityEntry existingEntry,EntitySet&amp; entitySet,Boolean&amp;   isNoOperation)at   System.Data.Entity.Core.Objects.ObjectContext.AttachTo(字符串   entitySetName,Object entity)at   System.Data.Entity.Internal.Linq.InternalSet 1.<>c__DisplayClassa.<Attach>b__9() at System.Data.Entity.Internal.Linq.InternalSet 1.ActOnSet(动作   action,EntityState newState,Object entity,String methodName)at   System.Data.Entity.Internal.Linq.InternalSet 1.Attach(Object entity)
at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value) at System.Data.Entity.Infrastructure.DbEntityEntry
1.set_State(EntityState   价值)在MUC.Controllers.MajorsController.Edit(主要专业,   HttpPostedFileBase img)中   C:\用户\三池\桌面\ MUC \ MUC \ \控制器MajorsController.cs:行   101.在System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase   controller,Object []参数)at   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext   controllerContext,IDictionary 2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary 2   参数)at   System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult的   asyncResult,ActionInvocation innerInvokeState)at   System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult 2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase 1.End()   在   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult的   asyncResult)at   System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()   在   System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters&LT;&GT; c__DisplayClass46.b__3f()

这是我的编辑视图:

@model MUC.Models.Major

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/ckeditor/ckeditor.js"></script>


    @using (Html.BeginForm("Edit", "Majors", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>Major</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.img, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @if (Model.img != null)
                    {
                        var base64 = Convert.ToBase64String(Model.img);
                        var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
                        <img src="@imgsrc" /><br/>
                        <input type="file" id="img" name="img"/>
                    }
                    else
                    {
                        <input type="file" id="img" name="img"/>
                    }

                    @Html.ValidationMessageFor(model => model.img, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.info, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.info, new { htmlAttributes = new { @id = "info", @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.info, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.whatThisTeach, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextAreaFor(model => model.whatThisTeach, new { htmlAttributes = new { @class = "form-control", @id = "whatThisTeach" } })
                    <script type="text/javascript">CKEDITOR.replace('whatThisTeach');</script>
                    @Html.ValidationMessageFor(model => model.whatThisTeach, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.whatToKnow, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.TextAreaFor(model => model.whatToKnow, new { htmlAttributes = new { @class = "form-control", @id = "whatToKnow" } })
                    <script type="text/javascript">CKEDITOR.replace('whatToKnow');</script>
                    @Html.ValidationMessageFor(model => model.whatToKnow, "", new { @class = "text-danger" })
                </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 to List", "Index")
    </div>
</body>
</html>

0 个答案:

没有答案