JQuery.Ajax with MVC

I am trying to use jQuery ajax to store the value that the user entered into the text box in the database. But I am amazed how to proceed. What i have done so far:

The user presses a button and I call the jQuery function and call the controller

comments = $("#txtComments").val(); var request = $.ajax({ url: "/Home/SaveCommentsData", type: "POST", data: { comment: comments }, dataType: "json" }); 

and I'm not sure how to get this comment value in the controller and send the value back to jQuery on success.

+4
source share
4 answers

try data like this

data: {'comment': comments}

and use the same variable as the string type in the 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) { // } 

Hello

+6
source

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); } 
+6
source

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}); } 
+2
source

try it

 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 }); } 
+2
source

All Articles