2013-01-23 32 views
2

我想要一個變量傳遞給我的JsonResult但她得到NUL所以這裏是從我的JsonResult和jQuery我的代碼難度在MVC 4使用JSON用ajax

[HttpPost] 
    public JsonResult MostraTela(Teste testea) 
    { 

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

和:

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? 我加緊數據:{testea:testea},錯誤,如果我踩到數據:testea,一切都在我的JsonResult自帶空

我的模型:

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; } 

} 

回答

2

嘗試給testea變量名,以確保操作方法將其分配給同一命名參數,就像這樣:

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

謝謝工作* - * – user2004932

+0

@ user2004932沒有問題,但爲什麼你不接受答案? – mattytommo

+0

我接受了答案,你對這個新問題有了新的答案? – user2004932

0

由於目標方法的簽名是一個字符串,嘗試傳遞123作爲一個字符串,前。

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

我試圖更即將來臨空 – user2004932

+0

我覺得@ mattytommo的是在正確的軌道上,但仍然分配testea爲字符串。 –

0

,如果你要通過JSON的content-type設爲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', 
}); 

控制器:

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

類:

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

如何在控制器中獲取模型?我試過這個,但得到空 – user2004932

+0

這段代碼適用於我,看你的模型和你的json是否有相同的屬性名 – lante