在我的视图中我有这样的事情:
<div class="form-group">
<form asp-controller="Ticket" asp-action="Comment" method="post">
<label asp-for="Comment" class="control-label"></label>
<textarea asp-for="Comment.Content" class="form-control" placeholder="Add comment!"></textarea>
<span asp-validation-for="Comment.Content" class="text-danger"></span>
</form>
<input type="submit" value="Add comment" class="btn btn-default" />
这是在我的详细信息视图中。现在我想为我的模型添加评论
public class TicketCommentViewModel
{
public Ticket Ticket { get; set; }
public Comment Comment { get; set; }
}
和控制器:
public async Task<IActionResult> Comment(TicketCommentViewModel model)
{
var ticket = await _context.Tickets.FirstOrDefaultAsync(u => u.TicketId == model.Ticket.TicketId);
var user = await GetCurrentUserAsync();
if(ticket == null)
{
return NotFound();
}
model.Comment.SendTime = DateTime.Now;
model.Comment.TicketID = ticket.TicketId;
model.Comment.Ticket = ticket;
model.Comment.UserId = user.Id;
model.Comment.User = user;
_context.Comments.Add(model.Comment);
ticket.Comments = await _context.Comments.ToListAsync();
return View();
}
我有这个问题 - &gt;如何从第一个代码(添加注释)转到Controller,并将我的注释添加到DB。 有人可以帮助我吗? 感谢。
答案 0 :(得分:1)
我不确定问题是什么,但我想当您点击提交时,您的数据未提交。这是因为您的提交按钮位于<form>.
之外尝试移动<form>
答案 1 :(得分:0)
//Two action methods in the controller
public ActionResult AddComment(int PageId, string name, string email, string comment)
{
Comment comment = new Comment()
{
PageID = PageId,
Name = name,
Email = email,
Comment = comment,
CreateDate = DateTime.Now
};
DbContext.Add(jobOffer);
return PartialView("ShowComments", DbContext.Where(c=> c.pageID == PageId));
}
public ActionResult ShowComments(int PageId)
{
return PartialView(DbContext.Where(c=> c.pageID == PageId));
}
//Add the script after the comment div in the View
<script>
function addComment() {
$.ajax({
url: "/Comment/AddComment/"+@Model.PageID,
type: "Get",
data: {
name: $("#txtName").val(), email: $("#txtEmail").val(),
comment : $("#txtComment").val() }
}).done(function(result) {
$("#offerList").html(result);
$("#txtName").val("");
$("#txtEmail").val("");
$("#txtComment").val("");
});
}
</script>