user2004932
user2004932

Reputation: 23

Difficulty in MVC 4 with Json using ajax

I'm trying to pass a variable to my JsonResult but she gets nul so here are my codes from my JsonResult and jQuery

    [HttpPost]
    public JsonResult MostraTela(Teste testea)
    {

        return Json(new { success = true });
    }

and :

   var testea = JSON.stringify(dado);
                    $.ajax({
                        url: '/Home/MostraTela',
                        type: 'POST',
                        dataType: 'json',
                        contentType: "application/json; charset=utf-8",
                        data: {testea: testea },
                        success: function (data) {
                            alert(data.success);
                        },
                        error: function () {
                            alert("error");
                        },

                    });

Agora eu fui tentar passar uma model e esta esta recebendo nulo novamente alguma ideia do que pode ser? I step up data: {testea: testea}, the error and if I step data: testea, everything comes null in my JsonResult

My model:

public class Teste
{
    public int idteste { get; set; }
    public string name { get; set; }
    public int age { get; set; }
    public string birthday { get; set; }
    public string salary { get; set; }

}

Upvotes: 2

Views: 1562

Answers (3)

lante
lante

Reputation: 7336

if you are going to pass JSON, set the content-type to application/json.

$.ajax({
    type: 'POST',
    url: '@Url.Action("MostraTela", "Home")',
    data: { Id: 1, Name: 'Im a complex object' },
    success: function (data) {
        alert(data.success);
    },
    dataType: 'json',
    contentType: 'application/json, charset=utf-8',
});

Controller:

[HttpPost]
public JsonResult MostraTela(MyModel model, FormCollection collection)
{
    return Json(new { success = true });
}

Class:

public class MyModel
{
    public string Name { get; set; }
    public int Id { get; set; }
}

Upvotes: 0

Mathew Thompson
Mathew Thompson

Reputation: 56429

Try giving the testea variable the name to make sure the action method assigns it to the same named parameter, like this:

$.ajax({
    url: url,
    type: "post",
    data: { testea: testea },
    dataType: 'json',
    success: function (data) {
        alert(data.success);
    },
   error: function () {
       alert("error");
    }
});

Upvotes: 2

ron tornambe
ron tornambe

Reputation: 10780

Since the signature of the target method is a string, try passing 123 as a string, ex.

var testea = JSON.stringify("123");

Upvotes: 0

Related Questions