2014-11-13 65 views
0

問題我正在使用ajax來確定何時更改下拉列表值,並將3個下拉列表的值傳遞給確定價格的方法。我使參數成爲動態的,並且我創建了一個類來存放數據,但是在getNewPrice方法中,當我嘗試訪問var item信息時,我得到一個null值。我對這個東西仍然很陌生,但我得到了這個概念,我很困惑如何將動態變量轉換回字符串,以便我可以訪問這些信息。將動態變量轉換爲類

$(document).ready(function() { 
    $('#documentTypeList').change(function() { 
     var modelData = { 
      documentType: $("#documentTypeList").val(), 
      urgency: $("#urgencyList").val(), 
      numberOfPages: $("#numberOfPagesList").val() 
     }; 
     $.ajax({ 
      type: "GET", 
      data: modelData, 
      url: "/Home/getNewPrice", 
      async: true, 
      success: function (result) { 
       document.getElementById('priceLabel').innerHTML = data.currentPrice; 
      } 
    }); 
    }); 

    public class modelData 
    { 
     public string documentType { get; set; } 
     public string numberOfPages { get; set; } 
     public string urgency { get; set; } 
    } 

    public JsonResult getNewPrice(modelData dropdownValues) 
    { 
     decimal currentPrice = Convert.ToDecimal(dropdownValues.urgency); 
     // do something with value and return a decimal 
     return Json(new { currentPrice = currentPrice }, JsonRequestBehavior.AllowGet); 
    } 
+2

這裏的動態有什麼好處?你只是馬上投下 – Jonesopolis

+0

我對ajax不熟悉,而動態類型是我能想到的唯一的東西 – user3610374

回答

0

模型聯編程序需要知道您的特定類型。它通過屬性循環並賦值。

嘗試

url: '/Home/getNewPrice', 
data: modelData 

public JsonResult getNewPrice(modelData dropdownValue) 
{ 
    //... 
    return Json(new { currentPrice = currentPrice }, JsonRequestBehavior.AllowGet); 
} 

document.getElementById('priceLabel').innerHTML = data.currentPrice; 
+0

我運行了你建議的代碼,它現在認識到modelData類是好的,但它不會' t似乎正在傳遞下拉值,因爲類中的所有值都爲空。我更新了上面的新代碼 – user3610374

+0

成功回調需要傳入數據:'success:function(data){...}' – beautifulcoder

1

我已經使用的JavaScript串行過去。使用deserialize()函數。 更具體=> C#

var list = serializer.Deserialize<List<GetJson>>(Request.Form["dataDetails"].ToString()); 

    internal class GetJson{ 
     public string variable1 {get;set;} //add your properties here 
    } 

Javascript 
        $.fn.serializeObject = function() { 
         var o = {}; 
         var a = this.serializeArray(); 
         $.each(a, function() { 
          if (o[this.name] !== undefined) { 
           if (!o[this.name].push) { 
            o[this.name] = [o[this.name]]; 
           } 
           o[this.name].push(this.value || ''); 
          } else { 
           o[this.name] = this.value || ''; 
          } 
         }); 
         return o; 
        }; 

        $.ajax({ 
         url: "url", 
         dataType: "json", 
         data: { 
          DataDetails: "[" + JSON.stringify($("#form1").serializeObject()) + "]" 
           }, 

如果需要它是更加動態則可以使用動態類型。

var list = serializer.Deserialize<List<dynamic>>(Request.Form["dataDetails"].ToString());