MVC给出的错误值不能为null或为空。当我在更新期间返回要查看的模型时

时间:2016-07-20 16:05:27

标签: asp.net-mvc razor

我正在尝试返回模型以查看保留用户在遇到异常时输入的数据。因此,当我返回模型进行查看时,它告诉我“值不能为空或空”但模型仍然具有数据

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

enter image description here

enter image description here

    [HttpGet]
    public ActionResult Edit(int? Id)
    {
        using (var db = new NewsDatabaseEntities())
        {
            db.Configuration.LazyLoadingEnabled = false;

            var Result = (from n in db.News.Include("Categories")
                          from c in db.Categories
                          where n.NewsId == Id
                          select new { news = n, neweCategories = n.Categories, cate = c }).ToList();


            News NewsDetails = (from news in Result
                                select new News
                                {
                                    NewsId = news.news.NewsId,
                                    NewsTitle = news.news.NewsTitle,
                                    NewsBody = news.news.NewsBody,
                                    NewsImagePath = news.news.NewsImagePath,
                                    Categories = news.neweCategories
                                }).FirstOrDefault();

            var AllCategories = (from c in Result
                                 select new Category
                                 {
                                     CategoryId = c.cate.CategoryId,
                                     CategoryName = c.cate.CategoryName
                                 }).ToList();



            if (NewsDetails != null)
            {

                var model = new NewsViewModel();
                model.NewsId = NewsDetails.NewsId;
                model.AllCategories = AllCategories;
                model.Categories = NewsDetails.Categories;
                model.NewsTitle = NewsDetails.NewsTitle;
                model.NewsBody = NewsDetails.NewsBody;
                model.NewsImagePath = NewsDetails.NewsImagePath;
                return View(model);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        return View();
    }





    [ValidateInput(false)]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(NewsViewModel model)
    {


        using (var db = new NewsDatabaseEntities())
        {
            db.Configuration.LazyLoadingEnabled = false;

            News NewsToUpdate = db.News.Include("Categories").SingleOrDefault(n => n.NewsId == model.NewsId);


            if (NewsToUpdate != null)
            {
                using (var transaction = db.Database.BeginTransaction())
                {

                    try
                    {

                        db.SaveChanges();

                        transaction.Commit();

                        return RedirectToAction("Details", "Admin", new { Id = model.NewsId });

                    }

                    catch (Exception ex)
                    {

                        transaction.Rollback();

                        TempData["Error"] = ex.Message + " " + ex.ToString();


                        return View(model);

                    }

                }

            }
            else
            {
                return RedirectToAction("Index", "Home");

            }

        }

        return View();
    }

Razor View

@model Assignment.Models.NewsViewModel

@{
    ViewBag.Title = "Edit";
}

<h2>Update News</h2>
<br />


@if (TempData["Error"] != null)
{
    <p class=" alert alert-danger">
        <strong>Error!  </strong>

        @TempData["Error"]

    </p>
}

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

    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })


        @Html.HiddenFor(model => model.NewsId)
        @Html.HiddenFor(model => model.SelectedCategoriesIds, new { id = "hid" })


        <div class="form-group">
            @Html.Label("Enter News Title", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.NewsTitle, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.NewsTitle, "", new { @class = "text-danger" })


                    <br /><br />
                    <img src="@Url.Content(Model.NewsImagePath)" alt="Image" id="ImagePreview" width=330 height=250 />
                <br /><br />

                    @Html.TextBoxFor(model => model.NewsImageFile, new { type = "file", data_val = "false" })
                @Html.ValidationMessageFor(model => model.NewsImageFile, "", new { @class = "text-danger" })


                <br /> <br />


                    <div class="form-group">

                        <div class="col-md-10">



                            @Html.TextAreaFor(model => model.NewsBody, new { htmlAttributes = new { @class = "ckeditor" } })
                            @Html.ValidationMessageFor(model => model.NewsBody, "", new { @class = "text-danger" })
                            <br />
                            This News under these categories: <br /><br />


                            <select id="dropdownOne" name="dropdownOne" multiple="multiple" class="form-control">


                                @foreach (var Category in Model.AllCategories)
                            {



                                if (Model.Categories.Select(c => c.CategoryId).Contains(Category.CategoryId))
                                {
                                    <option selected value="@Category.CategoryId">@Category.CategoryName</option>
                                }
                                else
                                {
                                    <option value="@Category.CategoryId">@Category.CategoryName</option>
                                }
                            }


                            </select>

                        </div>
                    </div>

                </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>


}

3 个答案:

答案 0 :(得分:0)

基本上,您编写的基础结构代码,而不是跨模型传递值的正确方法。在我的第一本书(现在是免费的pdf)中,我完成了整个项目并共享了代码,以及如何跨模型或视图模型进行数据绑定。无论如何,在这种情况下,尝试做一件事,将模型复制到会话中,然后从会话尝试分配相同的。我告诉你解决方法。虽然,我不喜欢编写代码的方式。继续按照设计模式,我在这里使用https://github.com/rahulsahay19/Movie-Review

答案 1 :(得分:0)

确保在HttpPost中返回View(模型)之前,在View中所需的HttpGet操作中所做的一切都已完成

        if (NewsDetails != null)
        {

            var model = new NewsViewModel();
            model.NewsId = NewsDetails.NewsId;
            model.AllCategories = AllCategories;
            model.Categories = NewsDetails.Categories;
            model.NewsTitle = NewsDetails.NewsTitle;
            model.NewsBody = NewsDetails.NewsBody;
            model.NewsImagePath = NewsDetails.NewsImagePath;
            return View(model);
        }

在第一次加载视图时设置所有属性值,但是当从失败的帖子返回时,其中一些值为null。您可以将@HiddenFor()用于某些未显示为Inputs的属性,但需要从上下文中重新填充List对象

答案 2 :(得分:0)

这是一个指向如何在MVC中执行CRUD的官方文档的链接:http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application

看一下Create场景。用户点击提交,并在服务器上检查是否有任何错误。如果模型中没有错误 - 我们提交。否则我们将错误添加到模型状态并再次返回模型以查看。这是代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate")]Student student)
{
    try
    {
        if (ModelState.IsValid)
        {
            db.Students.Add(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
    catch (DataException /* dex */)
    {
        //Log the error (uncomment dex variable name and add a line here to write a log.
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
    }
    return View(student);
}

在你的情况下

if (NewsDetails != null)
            {

                var model = new NewsViewModel();
                model.NewsId = NewsDetails.NewsId;
                model.AllCategories = AllCategories;
                model.Categories = NewsDetails.Categories;
                model.NewsTitle = NewsDetails.NewsTitle;
                model.NewsBody = NewsDetails.NewsBody;
                model.NewsImagePath = NewsDetails.NewsImagePath;
                return View(model);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }

如果出现错误,您将重定向到Index。并且您正在重定向到“索引”操作。正如有人在上面的评论中提到的那样 - 你需要确保Index操作在执行视图之前填满模型。

我粘贴的链接 - 也包含更新方案。只需浏览该文档并继续阅读。