2

I want to pass data between my view and my controller. I'm doing something wrong because it doesn't work.

JavaScript Front-end Code:

$.ajax({
    url: '@Url.Action("GetOid","SearchPerson")',
    data:  {oid : 1},
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        // return values 
        console.log("Success!" + data.oid); 
    },
    error: function () { console.log('error!!'); }
});

C# Controller Code:

    int CustomerId=0;

    [HttpPost]
    public ActionResult GetOid(int Oid)
    {

        // some code here to assign the value to a global var.
        CustomerId = Oid;

        ViewBag.id = Oid;


        return Json(new { oid = CustomerId });
    }

    });

4 Answers 4

2

Make this change to your ajax data property. It needs to be passed as string.

data: JSON.stringify({ "Oid": 1 }),

Also your controller parameters and data parameters are need to be same. The are case sensitive.

public ActionResult GetOid(int Oid)

Last as mentioned return it in json format.

return Json(new { oid = CustomerId });
Sign up to request clarification or add additional context in comments.

Comments

1

Javascript doesn't know anything about variables you set on the server. You need to return json to client like so:

 return Json(new { oid = CustomerId });

Comments

0

use

public JsonResult GetOid(int Oid)

to set the response headers properly

Comments

0

This baffled many newbies,

console.log("Success!" + **data.Data.oid**);

You should learn fire debugger on browser side and look at what concerns you on watch window.

1 Comment

i use firebug, but i test in chrome and ie. and yes, i'm newbie.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.