user2067567
user2067567

Reputation: 3813

jQuery.Ajax with MVC

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

Answers (4)

AliRıza Adıyahşi
AliRıza Adıyahşi

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

Satpal
Satpal

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

K D
K D

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

Sridhar Narasimhan
Sridhar Narasimhan

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

Related Questions