DotNetterNikhil

A Code Does it All

Send Data from Java Script to Controller in .NET MVC

timthumb

Now, When you are working on some Java script APIs or like for some other purpose you have to send java script data to Controller for storing that value in Database.

So, for that you have use the $.Ajax() for pass this java script data to controller.

and at Controller side, you can get that data easily…

As Like,

 

var uname = 'Nikhil Prajapati';

$.ajax({
        url: "/Main/getRequestID",      // This is path of your Controller with Action Result.
        dataType: "json",                // Data Type for sending the data
        data: {                         // Data that will be passed to Controller
                'my_name': uname,     // assign data like key-value pair
                  // 'my_name'  like fields in quote is same with parameter in action Result
        },
        type: "POST",                  // Type of Request

        contentType: "application/json; charset=utf-8", //Optional to specify Content Type.

        success: function (data) { // This function is executed when this request is succeed.
                alert(data);
        },
        error: function (data) {
                alert("Error");   // This function is executed when error occurred.
        }

});


Now, At Controller Side,

in MainController.cs

        public ActionResult getRequestID(String my_name)
        {
                MYDBModel myTable = new                 Models.MYDBModel();
                myTable.FBUserName = my_name;
                db.MYDBModel.Add(myTable);
                                db.SaveChanges();                          // db object of our DbContext.cs.
                //return RedirectToAction(“Index”);      // After that you can redirect to some pages…
                return Json(true, JsonRequestBehavior.AllowGet);    // Or you can get that data back after inserting into database.. This json displays all the details to our view as well.
        }

So, Yupp, you can pass the java script data easily to Controller..

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Information

This entry was posted on July 23, 2013 by in ASP.NET, MVC.
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: