MVC错误:对象引用未设置为@ Html.ValidationSummary上的对象实例

时间:2015-03-25 09:07:01

标签: asp.net-mvc

总是出错,我无法弄清楚我的代码的哪一部分会产生此错误?我试图将它与互联网上的其他情况进行比较,但仍无法追踪正在发生的事情。有人可以跟我分享你的建议吗?

这是我的观点:

  @model StockroomMaitenance.Models.PG_User

      @{
        ViewBag.Title = "Create";
       }

<h2>Create</h2>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)


    <p>
    <a href="@Url.Action("Users", "Admin", new { id = Model.User_Id })" data-original-title="Back to List" data-toggle="tooltip">
        <i class="glyphicon glyphicon-th-list"></i>Back to List</a>
</p>
<fieldset>
    <legend>PG_User</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.User_Id)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.User_Id)
        @Html.ValidationMessageFor(model => model.User_Id)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.User_BadgeId)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.User_BadgeId)
        @Html.ValidationMessageFor(model => model.User_BadgeId)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.User_FullName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.User_FullName)
        @Html.ValidationMessageFor(model => model.User_FullName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.User_Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.User_Email)
        @Html.ValidationMessageFor(model => model.User_Email)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.User_Role, "PG_Role")
    </div>
    <div class="editor-field">
        @Html.DropDownList("User_Role", String.Empty)
        @Html.ValidationMessageFor(model => model.User_Role)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.User_Password)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.User_Password)
        @Html.ValidationMessageFor(model => model.User_Password)
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

继承我的模特:

public partial class PG_User
{
    public PG_User()
    {
        this.PG_UserAct = new HashSet<PG_UserAct>();
        this.PG_Role1 = new HashSet<PG_Role>();
    }

    public int User_Id { get; set; }
    public string User_BadgeId { get; set; }
    public string User_FullName { get; set; }
    public Nullable<int> User_Role { get; set; }

    [Required(ErrorMessage = "Password is required")]
    [DataType(DataType.Password)]
    public string User_Password { get; set; }
    public string User_Email { get; set; }

    public virtual PG_Role PG_Role { get; set; }
    public virtual ICollection<PG_UserAct> PG_UserAct { get; set; }
    public virtual ICollection<PG_Role> PG_Role1 { get; set; }
  }  

这是我的控制器

    public ActionResult Users(string sortUser, string searchString)
    {
        if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
        {
            return RedirectToAction("Error", "Login");
        }

        else
        {
            ViewBag.NameSort = String.IsNullOrEmpty(sortUser) ? "User_FullName" : "";
            ViewBag.BadgeSort = sortUser == "User_BadgeId" ? "user_desc" : "User_BadgeId";

            var pg_user = db.PG_User.Include(p => p.PG_Role);
            if (!String.IsNullOrEmpty(searchString))
            {
                pg_user = pg_user.Where(s => s.User_FullName.Contains(searchString));
                if (pg_user != null)
                {
                          pg_user = pg_user.Where(s => s.User_FullName.Contains(searchString));
                }
                else
                {
                    ViewBag.NotFound = "No Results Found";
                }
            }

            switch (sortUser)
            {
                case "User":
                    pg_user = pg_user.OrderByDescending(s => s.User_FullName);
                    break;
                case "User_BadgeId":
                    pg_user = pg_user.OrderBy(s => s.User_BadgeId);
                    break;
                case "user_desc":
                    pg_user = pg_user.OrderByDescending(s => s.User_BadgeId);
                    break;
                default:
                    pg_user = pg_user.OrderBy(s => s.User_FullName);
                    break;
            }

            return View(pg_user.ToList());
        }
    }




    //
    // GET: /Admin/Details/5

    public ActionResult Details(int id = 0)
    {
        if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
        {
            return RedirectToAction("Error", "Login");
        }

        else
        {
            PG_User pg_user = db.PG_User.Find(id);
            if (pg_user == null)
            {
                return HttpNotFound();
            }
            return View(pg_user);
        }
    }

    //
    // GET: /Admin/Create

    public ActionResult Create()
    {
        if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
        {
            return RedirectToAction("Error", "Login");
        }

        else
        {
            ViewBag.User_Role = new SelectList(db.PG_Role, "Role_Id", "Role_Description");
            return View();
        }
    }
    //
    // POST: /Admin/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(PG_User pg_user)
    {
        if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
        {
            return RedirectToAction("Error", "Login");
        }

        else
        {
            if (ModelState.IsValid)
            {
                db.PG_User.Add(pg_user);
                db.SaveChanges();
                return RedirectToAction("Users");
            }

            ViewBag.User_Role = new SelectList(db.PG_Role, "Role_Id", "Role_Description", pg_user.User_Role);
            return View(pg_user);
        }
    }



    //
    // GET: /Admin/Edit/5

    public ActionResult Edit(int id = 0)
    {
        if (Session["LoggedUserRole"] == null && Session["LoggedUserFullname"] == null)
        {
            return RedirectToAction("Error", "Login");
        }

        else
        {
            PG_User pg_user = db.PG_User.Find(id);
            if (pg_user == null)
            {
                return HttpNotFound();
            }
            ViewBag.User_Role = new SelectList(db.PG_Role, "Role_Id", "Role_Description", pg_user.User_Role);
            return View(pg_user);
        }
    }

注意到有问题吗?

1 个答案:

答案 0 :(得分:1)

对于有同样问题的人来说,这个问题磕磕绊绊,这就是答案。

由于视图中的第一行@model StockroomMaitenance.Models.PG_User,这是一个强类型视图。

您必须将PG_User的实例传递给视图。

因此,在控制器操作public ActionResult Create()中,您应该更改

return View();

return View(new PG_User());

我不确定为什么会在@Html.ValidationSummary上抛出异常,但我已经测试了此修改并解决了问题(首先需要删除引用PG_RolePG_UserAct的代码。