Reputation: 3813
I am trying to use jQuery ajax to save the value that the user entered in the Textbox to the database. But I am struck how to proceed. What I did so far:
User clicks button and I call jQuery function and am calling the controller
comments = $("#txtComments").val();
var request = $.ajax({
url: "/Home/SaveCommentsData",
type: "POST",
data: { comment: comments },
dataType: "json"
});
and I am not sure how to get this comment value in the controller and send a value back to jQuery on success.
Upvotes: 3
Views: 9428
Reputation: 15876
script
$.ajax({
url: "/Home/SaveCommentsData",
type: "POST",
data: { comment: comments },
dataType: "json",
success: function (data) {
// data is returning value from controller
// use this value any where like following
$("#div_comment").html(data);
}
});
controller
[HttpPost]
public ActionResult SaveCommentsData(string comment)
{
// save comment
var result = someData; // maybe saved comment
return Json(result);
}
Upvotes: 6
Reputation: 133453
try this
comments = $("#txtComments").val();
var request = $.ajax({
url: '@Url.Action("SaveCommentsData","Home")',
type: "POST",
data: JSON.stringyfy({ 'comment': comments }),
dataType: "json",
success: function(data){
alert(data.status);
}
});
Controller
[HttpPost]
public JsonResult SaveCommentsData(string comment)
{
//Do something
return Json(new
{
status = false
});
}
Upvotes: 2
Reputation: 5989
client side script-jQuery
$.ajax({
url: "/Home/SaveCommentsData",
type: "post",
data: { comment: comments },
dataType: "application/json",
success: function (data) {
if(data.Success)
{
alert('Done');
}
}
});
controller side code
[HttpPost]
public ActionResult SaveCommentsData(string comment)
{
// save comment
return Json(new {Success:true});
}
Upvotes: 2
Reputation: 2653
try data like this
data :{'comment':comments}
and use the same variable as string type in controller action
comments = $("#txtComments").val();
var request = $.ajax({
url: "/Home/SaveCommentsData",
type: "POST",
data: { 'comment': comments },
dataType: "json"
});
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveCommentsData( string comment)
{
//
}
Regards
Upvotes: 6