ASP.NET MVC Binds Child Objects

I am working on an ASP.NET MVC 3 application. I have a Comment class that encapsulates the Post class (each comment is associated with a blog post), there is an action method for editing a comment, as shown below.

    [HttpPost]
    [Authorize(Users = admin)]
    public string EditComment(Comment comment)
    {
        //update the comment by calling NHiberante repository methods
    }

From javascript, I send only the values ​​of the comment object, such as the comment identifier, description to the server, so when I bind, I see the Post property inside the comment object as null, and when I do ModelState.IsValid, I become an empty error. My question is, how can I associate a post object with a comment? I can pass the message identifier to the server along with other values.

Thanks Vijaya Anand

+3
source share
2 answers

, , .

, , , , .

, :

public class Post
{
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    public string Content { get; set; }
}

public class Comment
{
    public int Id { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public string Content { get; set; }

    public Post Post { get; set; }
}

POST

, ( ) . , , ... . :

  • Post.Id(
  • Post.Title( , , , , - Post.Id; , )
  • - ( )
  • - ( )

Html- . post, .

Ajax POST

Ajax, , , jQuery .serialize(), $.ajax().

Javascript . JSON:

var comment = {
    Author: $("#Author").val(),
    Content: $("#Content").val(),
    Post: {
        Id: $("#Post_Id").val(),
        Title: $("#Post_Title").val()
    }
};

$.ajax({
    url: "someURL",
    type: "POST",
    data: $.toDictionary(comment),
    success: function(data) {
        // probably get a partial view with comment you can append it to comments
    },
    error: function(xhr, status, err) {
        // process error
    }
});

2 , :

  • Ajax ( ) .

  • () JSON $.toDictionary(), JSON, Asp.net MVC. .

+4

, TryUpdateModel UpdateModel . ( ), UpdateModel.

db ( ), .

:

       [HttpPost]
       [Authorize(Users = admin)]
        public string EditComment(int id, FormCollection form)
        {
               //update the comment by calling NHiberante repository methods

               // Fetch comment from DB
                var comment =  NHibernateHelper.Get<Comment>(id);

                // Update the comment from posted values
                TryUpdateModel(comment);

                // Handle binding errors etc.
                if (!ModelState.IsValid)
                {
                    // On error
                }

            // Commit to DB
            NHibernateHelper.Update<Comment>(comment);


            //Done!



        }

NHibernate, .

0

All Articles