【问题标题】:MVC gives Error Value cannot be null or empty. when i return model to view during updateingMVC 给出的错误值不能为空或为空。当我在更新期间返回模型以查看
【发布时间】:2016-07-21 08:58:24
【问题描述】:

如果出现异常,我正在尝试返回模型以查看以保留用户输入的数据。所以当我返回模型查看它告诉我“值不能为空或为空”但模型仍然有数据

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

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

剃刀视图

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


}

【问题讨论】:

  • 您认为哪一行出现错误?
  • @Shyju,谢谢你的帮助。这一行 Html.EditorFor(model => model.NewsTitle, new { htmlAttributes = new { class= "form-control" } })
  • 这通常是在发布后返回视图时未填充模型的所有属性的情况。在从 httppost 返回模型之前,您需要确保在初始 httpget 操作期间填充在模型上的任何属性也得到填充。以及您的视图需要的任何 ViewBag 或 TempData 对象也被设置
  • @JamieD77 非常感谢

标签: asp.net-mvc razor


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    确保在返回 HttpPost 中的 View(model) 之前,在 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() 用于某些不作为输入显示的属性,但需要从上下文中重新填充 List 对象

    【讨论】:

      【解决方案3】:

      这里是如何在 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

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

      [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。并且您正在重定向到索引操作。正如有人在上面提到的 cmets 中提到的那样 - 您需要确保 Index 操作在执行视图之前填充模型。

      我粘贴的链接 - 也包含更新场景。只需浏览该文档并继续操作即可。

      【讨论】:

        猜你喜欢
        • 2011-12-31
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 2016-03-25
        • 1970-01-01
        • 2021-09-02
        相关资源
        最近更新 更多