2013-02-01 3 views
0

나는 ASP.NET MVC에 웹 응용 프로그램을 구축 중입니다. 코멘트가 가장 오래된 것부터 가장 오래된 것까지 목록에 표시되고 사용자가 새로운 코멘트를 게시 할 수있는 맨 아래에 양식이있는 코멘트 페이지가 있습니다. 페이지에 최신 의견을 표시하는 것 외에도 양식 항목을 강조 표시해야합니다.댓글을 달아서 새 덧글을 추가 하시려면 같은 페이지에 양식을 게시하십시오

표시된 데이터와 게시 양식이 같은 페이지에있는 경우 가장 좋은 방법은 무엇입니까?

아약스 없이도이 작업을 수행 할 수 있습니까?

는 --Code는

class CommentsViewModel 
{ 
    public IList<Comment> comments { get; set; } 
    public Comment comment { get; set; } 
    public SelectList commentCategories { get; set; } 
} 


class Comment 
{ 
    [Required] 
    public string commentData { get; set; } 

    [Required] 
    public int? commentCategory { get; set; } 
} 


class Comments : Controller 
{ 

    public ActionResult Index() 
    { 
     Site db = new Site(); 
     CommentsViewModel commenstVm = new 
     { 
      comments = db.GetComments(), 
      comment = new Comment(), 
      commentCategories = db.GetCommentCategories() 
     }; 

     return View(commentsVm); 
    } 


    [HttpPost] 
    public ActionResult AddNewComment(CommentsViewModel commentVm) 
    { 
     Site db = new Site(); 
     if (!ModelState.IsValid) 
     { 
      return View("Index", commentVm); 
     } 
     db.AddComment(commentVm.comment); 

     return RedirectToAction("Index"); 
    } 
} 
+0

그것은 간단해야한다. 코드는 어떻게 생겼습니까? 주석을위한 모든 필드가있는 빈 폼을 렌더링 한 다음'View '에 전달 된'Model'을 반복 할 다른 영역을 렌더링하면됩니다. 자바 스크립트를 사용하여 가장 최근의 댓글을 강조 할 수 있습니다. –

+0

제목을 편집했습니다. "[제목에"태그 "가 포함되어 있어야합니까?] (http://meta.stackexchange.com/questions/19190/)"합의가 "아니오, 그렇지 않아야합니다"로 표시되어야합니다. –

+0

"페이지를 처리하는 가장 좋은 방법"이란 정확히 무엇을 의미합니까? – KodeKreachor

답변

1

여기 기본 View하고 시작점으로 사용할 수있는 Controller의 extract--.

모델과 뷰 모델 :

public class CommentsViewModel 
{ 
    public IList<Comment> comments { get; set; } 

    public CommentsViewModel() 
    { 
     comments = new List<Comment>(); 
    } 
} 

public class Comment 
{ 
    [Required] 
    public string commentData { get; set; } 
    /** Omitted other properties for simplicity */ 
} 

보기 :

@using (@Html.BeginForm("Index", "Comments")) 
{ 
    @Html.TextBoxFor(t => t.comment.commentData) 
    @Html.ValidationMessageFor(t=> t.comment.commentData, "", new {@class = "red"}) 
    <button name="button" value="addcomment">Add Comment</button> 
} 

@foreach (var t in Model.comments) 
{ 
    <div>@t.commentData</div> 
} 

컨트롤러 :

public class CommentsController : Controller 
{ 
    /** I'm using static to persist data for testing only. */ 
    private static CommentsViewModel _viewModel; 

    public ActionResult Index() 
    { 
     _viewModel = new CommentsViewModel(); 
     return View(_viewModel); 
    } 

    [HttpPost] 
    public ActionResult Index(Comment comment) 
    { 
     if (ModelState.IsValid) 
     { 
      _viewModel.comments.Add(
       new Comment() {commentData = comment.commentData}); 
      return View("Index", _viewModel); 
     } 

     return RedirectToAction("Index"); 
    } 
} 
관련 문제