从mvc中的数据库读取后的空值

时间:2015-09-26 11:15:36

标签: c# model-view-controller view null edit

我的博客控制器中有编辑视图和编辑操作。 在我使用"创建动作"创建了一个帖子后在我将图像上传到数据库文件夹后,我更新post.PostImage(字符串值)上的路径。 我可以看到文件夹中的图像,我可以看到图像的路径,我也可以在编辑视图中看到图片的预览。在我的数据库中,它保存为(〜/ Images / PostID / PictureName)。但是在我编辑我的帖子之后,我想制作一个复选框,如果选中,我可以编辑图片,什么时候不检查我删除图片。我发送参数,我的问题是在调试器上我看到"字符串postimage" as null但在数据库表上它有路径! 因为所有这些都不起作用,我不关心逻辑,为什么它是空的???? 这是我的代码:

查看:

@model WebApplication1.Models.Post

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

<h2>Edit</h2>


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

    <div class="form-horizontal">
        <h4>Post</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.PostID)

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

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

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

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

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

        <div class="form-group">  
            <div>
                <b>Upload image:</b>
                @if (!Model.PostImage.IsEmpty())
                {                    
                        @Html.CheckBox("checkImage", true)
                        <img src="@Url.Content(Model.PostImage)" alt="@Model.PostAuthor" width="300" />
                }

                else
                {
                    @Html.CheckBox("checkImage", false)
                }
            </div>            
            <input type="file" name="file" id="file" />
            <!-- Show message of the controller -->
            @ViewBag.Message
        </div>    

        <div class="form-group">
            @Html.LabelFor(model => model.PostVideo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PostVideo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PostVideo, "", 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 Posts List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

在博客控制器中编辑行动:

   // GET: Blog/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Post post = db.Posts.Find(id);
            if (post == null)
            {
                return HttpNotFound();
            }
            return View(post);
        }

        // POST: Blog/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "PostID,PostTitle,PostAuthor,WebSite,PostDate,PostText,PostImage,PostVideo")] Post post, HttpPostedFileBase file, bool checkImage)
        {
            var fileName = "";
            if (ModelState.IsValid)
            {
                db.Entry(post).State = EntityState.Modified;

                if (checkImage == true)
                {
                    //Check if there is a file
                    if (file != null && file.ContentLength > 0)
                    {
                        //Check if there is an image
                        var supportedTypes = new[] { "jpg", "jpeg", "gif", "png" };
                        var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);

                        if (!supportedTypes.Contains(fileExt))
                        {
                            ViewBag.Message = "Invalid image type. Only the following types (jpg, jpeg, gif, png) are supported";
                            return View();
                        }

                        //Check if there is a file on database
                        if ( !(String.IsNullOrEmpty(post.PostImage)) )
                        {                            
                            //Delete old file in folder                                                        
                            System.IO.File.Delete(post.PostImage);

                            //Save new file in folder
                            var folder = Path.Combine(Server.MapPath("~/Images/"), Convert.ToString(post.PostID));
                            var path = Path.Combine(folder, fileName);
                            file.SaveAs(path);

                            //Save path in database
                            string targetPath = String.Concat("~/Images/", Convert.ToString(post.PostID), "/", fileName);
                            post.PostImage = targetPath;
                        }

                        //No file in database
                        else
                        {
                            var folder = Path.Combine(Server.MapPath("~/Images/"), Convert.ToString(post.PostID));
                            var path = Path.Combine(folder, fileName);
                            file.SaveAs(path);

                            //Save path in database
                            string targetPath = String.Concat("~/Images/", Convert.ToString(post.PostID), "/", fileName);
                            post.PostImage = targetPath;
                        }
                    }

                    //Checkbox is checked but not file uploaded
                    else
                        ViewBag.Message = "Checkbox is checked, please upload an image";
                    return View();
                }

                else
                {
                    //Checkbox is not checked - Delete the image from database
                    if( !(String.IsNullOrEmpty(post.PostImage)) )
                    {
                        //Delete old file in folder                                                    
                        try
                        {
                            System.IO.File.Delete("\a.txt");
                            post.PostImage = null;
                        }
                        catch (System.IO.IOException e)
                        {
                            Console.WriteLine(e.Message);                                
                        }                                                                        
                    }

                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            return View(post);
        }

2 个答案:

答案 0 :(得分:0)

渲染postImage字段

@Html.EditorFor(model => model.PostImage, new { htmlAttributes = new { @class = "form-control" } })

答案 1 :(得分:0)

因此,根据我最近阅读的内容,不要将您的Entity Framework模型直接传递到您的视图中。创建一个单独的ViewModel。在GET上,根据您的EF模型构建此ViewModel,并在POST上,从ViewModel中提取所需信息,并更新数据库中的EF模型

在您的视图中,图片网址没有EditorFor()HiddenFor(),这就是为什么POST它将为空。

这就是为什么你要使用ViewModels而不是直接在视图中使用EF模型的原因,这样你就可以拥有一个单独的视图模型,它只包含需要编辑/更新/显示的属性,而属性来自需要保持不变的实体将保持不变。