2014-05-18 11 views
1

블로그를 작성하기 위해 MVC를 사용하고 있습니다. 내가 원한 것은 게시 코멘트를 데이터베이스의 해당 위치에 저장하는 것이지만 작동하지 않습니다. 다음과 같이양식에 데이터를 저장하지 않음

내 포스트 모델은 다음과 같이

public class Post 
{ 
    [Key] 
    public int PostId { get; set; } 
    public string Title { get; set; } 
    public DateTime CreatedDate{get;set;} 
    public DateTime UpdateDate { get; set; } 
    public string Body { get; set; } 
    public ICollection<Comment> Comments { get; set;} 
    public ICollection<Tag> Tags { get; set; } 

} 

내 의견 모델은 다음과 같습니다

public class Comment 
    { 

     [Key] 
     public int CommentId { get; set; } 
     public int PostId { get; set; } 
     [ForeignKey("PostId")] 
     public virtual Post Post{get; set;} 
     public string CommentCreateDate { get; set; } 
     public string CommentUpdateDate { get; set; } 
     public string CommeterName { get; set; } 
     public string EmailAddress { get; set; } 
     public string CommentText { get; set; } 
     public bool Approved { get; set; } 

    } 

을 내가 가지고있는 다음과 같은 작업 방법 :

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

    [HttpPost] 
    [ValidateInput(false)] 
    public ActionResult CreateComment(int id, string name, string email, string txt, bool aproved = false) 
    { 

     Post post = GetPost(id); 
     Comment comment = new Comment(); 
     comment.Post = post; 
     comment.CommentCreateDate = DateTime.Now.ToString(); 
     comment.CommeterName = name; 
     comment.EmailAddress = email; 
     comment.CommentText = txt; 
     comment.Approved = aproved; 
     db.Comments.Add(comment); 
     db.SaveChanges(); 

     m_commentList.Add(comment); 



     return RedirectToAction("CreateComment", new { id = id }); 

    } 

을 그리고 내보기 나는 이것을 시도하고있다 :

@model Blog.Models.Comment 

@{ 
    ViewBag.Title = "CreateComment"; 
} 

<h2>Create a Comment</h2> 


    @using (Html.BeginForm()) 
    { 
     <fieldset> 

      <legend>Enter Comment</legend> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.CommeterName) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.CommeterName) 
      </div> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.EmailAddress) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.EmailAddress) 
      </div> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.CommentText) 
      </div> 
      <div class="editor-field"> 
       @Html.TextAreaFor(model => model.CommentText) 
      </div> 
      <p> 
       <input type="submit" value="Create comment" /> 
      </p> 

     </fieldset> 

    } 

예외는 없지만 양식의 데이터는 저장되지 않습니다. 조치 결과에 설정된 데이터, 즉 CommentCreateDate W Approved. 내가 뭘 잘못하고 있는지 모르겠다.

@using (Html.BeginForm(new {id = Model.CommentId})) 
{ 
    <fieldset> 

     <legend>Enter Comment</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.CommeterName) 
     </div> 
     <div class="editor-field"> 
      @Html.TextBoxFor(model => model.CommeterName) 
     </div> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.EmailAddress) 
     </div> 
     <div class="editor-field"> 
      @Html.TextBoxFor(model => model.EmailAddress) 
     </div> 
     <div class="editor-label"> 
      @Html.LabelFor(model => model.CommentText) 
     </div> 
     <div class="editor-field"> 
      @Html.TextAreaFor(model => model.CommentText) 
     </div> 
     <p> 
      <input type="submit" value="Create comment" /> 
     </p> 

    </fieldset> 

} 

이 나에게 내가 새로운 키워드를 사용하는 경우에도 null 참조 예외를 줄 것이다 :

나는 다음과 같이 BeginForm()에서 주석의 ID를 포함하는 제 2 옵션을 시도

System.NullReferenceException: Object reference not set to an instance of an object. 

왜 이런 일이 발생합니까? 아무도 도와 줄 수 있니?

답변

2

액션의 서명이 있어야한다 감사 : 양식 필드에 대해 생성

public ActionResult CreateComment(Comment model) 

이름은 같은 모델 클래스의 속성에 다시 바인딩합니다. 예를 들어 CommenterName 속성이 동작의 name 매개 변수와 일치해야한다는 것을 프레임 워크에서 알 수있는 방법이 없습니다.

두 번째 예는 거의 의미가 없습니다. ID를 작성하려고했지만 사용자가 설정하지 않은 경우입니다. 또한

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

당신은 당신이 당신의 모델과 행동에 노출 필드 것을주의해야한다 : 당신이 NullReferenceException을받을 이유는 사실, 당신은 짝수 형태로보기에 Comment를 전달하지 않습니다. 예를 들어, 사용자는 쉽게 자신의 의견을 강요 할 수 브라우저의 개발 콘솔을 통해 다음과 같은 마크 업을 추가하여 단지 승인을 받아야 : 설정할 수있는 모델의 특성 중 하나입니다

<input type="hidden" name="approved" value="true" /> 

아무것도하거나 행동 에 대한 매개 변수 사용자가.

[HttpPost] 
public ActionResult CreateComment(CommentViewModel model) 
{ 
    var comment = new Comment(); 
    comment.CommenterName = model.Name; 
    // etc... 
} 

이 사용자를 방지 :

public class CreateCommentViewModel 
{ 
    public string Name { get; set; } 
    public string Email { get; set; } 
    public string Text { get; set; } 
} 

은 다음과 액션에 Comment이지도하는 :

모두 더 나은 옵션은 양식을위한 전용 모델 클래스를 사용하는 것 ApprovedCreatedDate과 같은 것을 설정할 수 없습니다.

+0

답변 해 주셔서 감사합니다. 반환은 무엇입니까? – bluetxxth

+0

당신이 필요로하는 것은 무엇이든지 - 나는 단지 당신이 모델 바인딩을 할 수있는 더 좋은 방법을 보여주기 위해 노력하고 있습니다. 나머지는 당신에게 달렸습니다. –

+0

도움 주셔서 감사합니다 !!! 그러나 여전히 서명과 같은이 ID를 전달하는 데 필요한 : public ActionResult CreateComment (int? id, CommentViewModel model) – bluetxxth

관련 문제