Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi every i need help about how to retrieve a variable value from javascript code and pass it to my controller, i'm using mvc 5 asp.net and i'm a beginner
Posted
Comments
Sandeep Singh Shekhawat 17-Apr-14 0:14am    
Can you please more clear this question? Why are you not trying jQuery.ajax() method to call controller action method in url and pass parameter as a "data" property of it.

One option is to pass this value via an ajax call (using JQuery).
In Javascript, use this
function getVal(id) {
    $.ajax({
        url: '@Url.Action("Action1", "Controller")',
        type: 'GET',
        dataType: 'json',
        cache: false,
        data: { id: id },
        success: function(person) {
            //Do something
        }
    });
}


In your controller, you will get id -
C#
[HttpGet]
public ActionResult Action1(string id)
{
  //Do something
}
 
Share this answer
 
Comments
Sanket Saxena 17-Apr-14 5:30am    
This should work..
Hi, I think you must first learn 'JavaScript' or 'JQuery'. And also learn AJAX, as it is frequently used in the MVC.
JavaScript
//For fetching the variable value using JavaScript
var a = document.getElementById("variableID").value;

JavaScript
$.ajax({
       url: "/ControllerName/ActionName",
       // a stands for the variable considered above.
       data: {a},
       dataType: "JSON",//You can use other datatype as per your need
       type: "POST",
       error: function (jxr, status, error) {
            HandleAjaxError(jxr, status, error);
       },
       // 'data' will contain the return values of the Action
       success: function (data) {
       var sReturn = data;
       if (sReturn == 1) {
          alert('Your Message');
       }
       else {
          alert('Your Message');
       }
      }
 });


Place below code above the controller action defination, which you will call through AJAX. It specifies that particular action is for 'POST'.
C#
[HttpPost]
public ActionResult ActionName{}
{
}
 
Share this answer
 
v2
Elaborate more my friend, seems you need to send data from client side to server side as an AJAX call, when do you want this to happen? on submitting the form or when doing an AJAX call to the server?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900