保存到数据库时模型评估为false

时间:2014-11-25 18:59:38

标签: asp.net-mvc-4

因此,在我的asp.net mvc4 Web应用程序中尝试将项目保存到数据库时遇到此问题。 我有三个课程列在下面

public class Posts
{
    [Key]
    public int PostID { get; set; }

    [Required(ErrorMessage="A Title is required for your Post")]
    [Display(Name="Title")]
    public string PostTitle { get; set; }


    [Required(ErrorMessage="This Field is Required")]
    [Display(Name = "Post")]
    public string PostContent { get; set; }

    [Required()]
    [DataType(DataType.DateTime)]
    public DateTime PostDate { get; set; }
    //public int AuthorID { get; set; }
    //public int CommentID { get; set; }

    [NotMapped]
    public virtual List<Comments> Comment { get; set; }
    public virtual Users user { get; set; }

}

此类与下面的用户类有多对一的关系

public class Users
{

    public Users()
    {
    }

    [Key]
    public int UserID { get; set; }

    [Required()]
    public string Firstname { get; set; }

    [Required()]
    public string Lastname { get; set; }

    [Required()]
    [DataType(DataType.Date, ErrorMessage="Enter a Valid Date")]
    public DateTime DOB { get; set; }

    //[Required()]
    //public string Photo { get; set; }

    [Required()]
    public string Sex { get; set; }

    [Required()]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    public DateTime RegDate { get; set; }

    [Required()]
    [Column("Username")]
    //[Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name has already been taken. Please enter a different User name.")]
    public string Username { get; set; }

    [Required()]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public string PasswordSalt { get; set; }

    [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage="Passwords do not match")]
    [DataType(DataType.Password)]
    //[NotMapped]
    //public string ConfirmPassword { get; set; }


    public virtual List<Posts> Post { get; set; }
    public virtual List<Comments> Comment { get; set; }

}

Posts.cs类的数据库表有一个名为user_UserID的字段,我假设它是存储创建帖子的用户的id。我正在尝试使用以下代码将帖子保存到数据库

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

<fieldset>
    <legend>Posts</legend>

    <div class="form-group">
        @Html.LabelFor(model => model.PostTitle)
        @Html.TextBoxFor(model => model.PostTitle, new {@class = "form-control"})
        @Html.ValidationMessageFor(model => model.PostTitle)
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.PostContent)
        @Html.TextAreaFor(model => model.PostContent, new {@class = "form-control"})
        @Html.ValidationMessageFor(model => model.PostContent)
    </div>
        <input type="hidden" name="user.UserID" value="@Session["LoggedUserID"]" />

    <div>
        <input type="submit" value="Submit" />
    </div>
</fieldset>

}

如您所见,我保存到数据库表的用户ID来自存储在Session["LoggedUserID"]变量中的用户ID。处理保存的控制器低于

public class PostsController : Controller
{
    //
    // GET: /Posts/
    BlogContext db = new BlogContext();
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Create(Posts Post)
    {
        var errors = ModelState.Values.SelectMany(v => v.Errors);
        try
        {
            if (ModelState.IsValid)
            {
                var newPost = db.Post.Create();
                newPost.PostTitle = Post.PostTitle;
                newPost.PostContent = Post.PostContent;
                newPost.PostDate = DateTime.Now;
                newPost.user.UserID = Post.user.UserID;
                db.Post.Add(newPost);
                db.SaveChanges();
                return RedirectToAction("Index", "Posts");
            }
            else
            {
                ModelState.AddModelError("", "Something is wrong with the model");
            }
        }

        catch (NullReferenceException ex)
        {
            Debug.WriteLine("Processor Usage" + ex.Message);
        }

        return View();
    }

}

我将断点附加到Modelstate.IsValid行然后进行了调试,但我注意到ModelState总是评估为false而ModelState.AddModelError显示验证有问题该模型。我试过所有可能的调整都无济于事。我需要帮助。如何在没有此问题的情况下将帖子保存到数据库表中。 请问我做错了什么?

1 个答案:

答案 0 :(得分:0)

我怀疑ModelState无效,因为您正在发布user.UserId(隐藏输入)的值,该值正在初始化属性User,由于应用于其他的验证属性,该属性无效User的属性。最好创建一个视图模型来创建只包含显示/编辑所需属性的新Posts。没有必要为User(帖子的作者)包含属性,因为这可以在保存数据时在控制器中设置(类似于您对PostDate属性的操作< / p>

查看模型

public class PostVM
{
  [Required(ErrorMessage="A Title is required for your Post")]
  [Display(Name="Title")]
  public string Title { get; set; }
  [Required(ErrorMessage="This Field is Required")]
  [Display(Name = "Post")]
  public string Content { get; set; }
}

控制器

[HttpGet]
public ActionResult Create()
{
  PostVM model = new PostVM();
  return View(model);
}

[HttpPost]
public ActionResult Create(PostVM model)
{
  if(!ModelState.IsValid)
  {
    return View(model);
  }
  // Initialize new Posts
  // Map properties from the view model, set the user and date
  // Save and redirect
}

查看

@model PostVM
@using (Html.BeginForm()) {
  ....
  <div class="form-group">
    @Html.LabelFor(model => model.Title)
    @Html.TextBoxFor(model => model.Title, new {@class = "form-control"})
    @Html.ValidationMessageFor(model => model.Title)
  </div>
  <div class="form-group">
    @Html.LabelFor(model => model.Content)
    @Html.TextAreaFor(model => model.Content, new {@class = "form-control"})
    @Html.ValidationMessageFor(model => model.Content)
  </div>
  <input type="submit" value="Submit" />
}