i am having a problem while retrieving the data coming from Json...
i am passing some values through $.ajax and i want to process that values in the controller..
please help, how can i retrieve the values in controller...
Jquery Code
var userID = @Model.User.UserID;
var postID = @Model.Post.PostID;
var commentBody = $('#textareaForComment').val();
$('#btnSubmit').click(function (e)
{
e.preventDefault();
var postdata =
{
CommentBody: commentBody,
PostID: postID,
UserID: userID
};
$.ajax({
url: '@Url.Action("SubmittedComment","Post")',
data: postdata,
success: function(data) {
$('#showComments').html(data);
}
});
});
now i am calling the SubmittedComment Action in the Post controller and i want to have the PostID,USerID and the CommentBody in that action and want to store it in a diff variable..
please help. thx
controller code
public JsonRe开发者_开发问答sult SubmittedComment(string CommentBody,UserID,PostID)
{
var result = CommentBody // i am not able to get the value here ....
}
$('#btnSubmit').click(function () {
$.ajax({
url: '@Url.Action("SubmittedComment","Post")',
// Values should be evaluated at the callback, not at page load time
// this is not the case for UserID and PostID, but for CommentBody it is
data: {
UserID: @Model.User.UserID,
PostID: @Model.Post.PostID,
CommentBody: $('#textareaForComment').val()
},
success: function(data) {
// Controller action returns data in Json format, so .html() makes no sence here.
// Change action to return html markup via PartialView or change this function to
// parse Json. Also, returning Json via GET request is forbidden by default by ASP.NET MVC (just in case you don't know
$('#showComments').html(data);
}
});
return false; // Equals to e.preventDefault()
});
Your jQuery ajax call is not performing an HTTP POST
.
EDIT: Note that you should also be evaluating $('#textareaForComment').val()
in your button click event, as Artem pointed out.
Add the option type: 'POST'
to your call:
$('#btnSubmit').click(function (e)
{
e.preventDefault();
var postdata =
{
CommentBody: $('#textareaForComment').val(),
PostID: postID,
UserID: userID
};
$.ajax({
url: '@Url.Action("SubmittedComment","Post")',
data: postdata,
type: 'POST',
success: function(data) {
$('#showComments').html(data);
}
});
});
Alternatively, use the post()
function:
$.post('@Url.Action("SubmittedComment","Post")',
postdata,
success: function(data) {
$('#showComments').html(data);
}
);
You will also want to add the [HttpPost]
attribute to your controller action to restrict the exucution of the method to HTTP POST only:
[HttpPost]
public JsonResult SubmittedComment(string CommentBody, int UserID, int PostID)
{
// ... snip ...
}
精彩评论