0

My action method takes a custom C# class - Comment.cs :

public class Comment
{
  public int ID {get; set;}
  public int CardID {get; set;}
  public int UserID {get;set;}
  public string Comment {get;set;}
}

In my view I have a form with input fields for each property in the class except for ID (it's generated by the database). I prevent the default behavior on form submission with jquery and use $.post like this -

$('.form').on('submit', function(e) {
  e.preventDefault();
  var comment = this.Comment.value;
  var cardId = this.CardID.value;
  var userId = this.UserID.value;
  $.post('/Cards/AddComment',
      {
        Comment: comment,
        CardID: cardId,
        UserID: userId
      });
});

Html -

<form asp-controller="Cards" asp-action="AddComment" id="comment-form">
    <input class="form-control" name="Comment" placeholder="Leave a comment.." />
    <input class="form-control" name="CardID" type="hidden" />
    <input class="form-control" name="UserID" value="@User.Claims.ElementAt(0).Value" type="hidden" />
    <input type="submit" />
</form>

action method -

public IActionResult AddComment(Comment comment)
{
  // comment.Comment == null
  // comment.CardID == null
  // comment.UserID == null
}

I'm trying to automagically cast my posted jQuery data to a Comment type but it isn't working.

Cory Kleiser
  • 1,969
  • 2
  • 13
  • 26
Jessie Cryer
  • 159
  • 2
  • 9
  • What exactly are you trying to do? – MSH May 07 '18 at 20:08
  • You described how to do it :) So what it is the problem? – AlbertK May 07 '18 at 20:48
  • It isn't working? I've debugged and the properties of the Comment are null. They aren't bound to the object. – Jessie Cryer May 07 '18 at 20:56
  • 1
    Everything looks correct except of `Comment.Comment` property. You will get a compile error related to property name. Also post your html – AlbertK May 07 '18 at 21:57
  • Nah that property isn't going to cause a compile error. it's comment.Comment. lowercase.Uppercase – Jessie Cryer May 07 '18 at 21:58
  • @Albert You say everything looks correct? Like is that how model binding works, it's that simple? – Jessie Cryer May 07 '18 at 22:01
  • yes. Just tried it and default model binder works. Two things I changed: 1) Renamed class `Comment` to `CommentModel` to escape the compile error. 2) Set `value` attributes for all three inputs in markup directly. – AlbertK May 07 '18 at 22:29

0 Answers0