2016-12-14 63 views
2

每個解決方案/類似的問題都與json對象有關。我認爲這個問題可能是由使用html造成的。我也驗證過,在碰到ajax調用之前數據不是空的。MVC:Ajax數據沒有得到控制器

這裏是阿賈克斯

function SubmitSearch() { 
    var type = $("#select_SearchType").val() 
    var query = $("#input_Search").val() 

    $.ajax({ 
     //url: "newSearch", 
     url: '@Url.Action("newSearch", "Results")', 
     type: 'POST', 
     cache: false, 
     dataType: "html", 
     contentType: 'application/html; charset=utf-8', 
     data: { type: type, query: query }, 
     success: function (ViewModel) { 
      alert(ViewModel) 
      $("#div_record").empty(); 
      $("#div_record").html(ViewModel) 
     }, 
     error: function (ViewModel) { 
      alert("error") 
      $("#div_record").empty(); 
      $("#div_record").html(ViewModel) 
     }, 
    }); 
} 

和選定的代碼從操作

[HttpPost] 
    public ActionResult newSearch(string type, string query) 
    { 
     switch (type) 
     { 
      case " ": 
       response.errMess = "empty data, T:" + type + " Q:" + query; 
       return PartialView("Record", response); 
      default: 
       response.errMess = "Error: mismatched fields, T:" + type + " Q:" + query; 
       return PartialView("Record", response); 
     } 

類型和查詢都變爲空

+0

爲什麼你'的contentType:「應用程序/ HTML; charset = utf-8''當你實際發佈'application/x-www-form-urlencoded'時?如果您希望在* response *中使用HTML,則dataType:'html''就足夠了。 contentType由* request *使用。 – haim770

+0

我認爲這是正確的,因爲我發送的對象類型只是純文本字符串 –

+0

感謝它的工作! –

回答

2

你並不需要使用contentType: 'application/html; charset=utf-8'。有一些方法。

首先,你必須使用像這樣(把參數直接url):

$.ajax({ 
    //url: "newSearch", 
    url: '@Url.Action("newSearch", "Results")?type='+type+'&query='+query, 
    type: 'POST', 
    success: function (ViewModel) { 
     alert(ViewModel) 
     $("#div_record").empty(); 
     $("#div_record").html(ViewModel) 
    }, 
    error: function (ViewModel) { 
     alert("error") 
     $("#div_record").empty(); 
     $("#div_record").html(ViewModel) 
    }, 
}); 

二。 您必須使用data屬性將一些數據保存到服務器。

如果你想返回PartialView,就沒有必要使用dataType: "html"

事情是這樣的:

$.ajax({ 
    //url: "newSearch", 
    url: '@Url.Action("newSearch", "Results")', 
    type: 'POST', 
    cache: false, 
    data: { type: type, query: query }, 
    success: function (ViewModel) { 
     alert(ViewModel) 
     $("#div_record").empty(); 
     $("#div_record").html(ViewModel) 
    }, 
    error: function (ViewModel) { 
     alert("error") 
     $("#div_record").empty(); 
     $("#div_record").html(ViewModel) 
    }, 
}); 
+0

由於該操作返回了「PartialView」,因此OP正確地期待HTML返回。使用'dataType:'json''會阻止這種情況。 – haim770

+0

是的,你是對的。謝謝。我沒有看到該方法返回'partialView'。 –