Silviu Preda
Silviu Preda

Reputation: 628

Javascript null value sent erroneously to method

Javascript code:

var x = null;
var action_data = {x:x};
$.get(
  '~/MyController/MyAction',
  action_data,
  function(result){
    //do_something
  }
);

Controller action:

public class MyController: Controller{
  ...
  public ActionResult MyAction(string x)
  {
    //here, x is the string 'null';

  }
}

Can someone explain to me why the string "null" is sent to the action instead of the value null? Thanks

Upvotes: 0

Views: 42

Answers (2)

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

because u passed data null which converted to string and set to your action:

var x = null;
x="any thing"; // you need to change x value to be sent here
var action_data = {x:x};
$.get(
  '~/MyController/MyAction',
  action_data,
  function(result){
    //do_something
  }
);

if you want to pass null:

var x;
var action_data = {x:x};
$.get(
   '~/MyController/MyAction',
   action_data,
   function(result){
     //do_something
   }
 );

Upvotes: 1

Silviu Preda
Silviu Preda

Reputation: 628

Ok, so thanks to Ahmed, i came up with the solution:

var x; //without the null initialization

does the trick ;)

Upvotes: 0

Related Questions