2016-01-25 35 views
1

null以下位代码应该检索任何具体的价格日期/价格日期ID的记录价格。除了传递给Controller的值总是为null,“undefined”,“”,或者作为字符串传递时否则缺少一个值,并且不传递/在View中传递错误时一个int。我为这个问题使用了一个模板,但我看不到这里发生了什么。不考虑可能会出现另一个问题的最终计算结果,任何人都可以发现ID值未被传递的原因吗?提前致谢!AJAX获取呼叫发送到控制器

HTML:

<div class="col-lg-8"> 
    @Html.LabelFor(m => m.PriceDate, "Pricing Date") 
    @Html.DropDownListFor(m => m.PriceDate, Model.PricingDates, "--New Pricing--") 
</div> 

脚本:

$(function() { 
    var $priceValue = $("#PriceDate").val(), 
     $pID = { iD: $priceValue }; 
     $("#PriceDate").change(function() { 
     if ($(this).val()) { 
     //make AJAX call for historical Price data and populate table 
      $.ajax({ 
       type: "GET", 
       url: '@Url.Action("GetPrices", "Sales")', 
       data: $pID, 
       success: function (data) { 
       //Fill data 
        $("#Prices").val(data); 
       } 
      }); 
     } 
     else { 
      //clear data 
      $("#Prices").val(''); 
     } 
     }).change(); 
}); 

控制器:

public ActionResult GetPrices(string iD) 
{ 
    int priceID; 
    Int32.TryParse(iD, out priceID); 
    //priceID = iD; 

    dbEntities db = new dbEntities(); 
    var selectedPrice = new List<PricesModel>(); 
    var accountPrices = db.uspGetPrices(priceID); 

    //Do stuff 

    return Json(selectedPrice, JsonRequestBehavior.AllowGet); 
} 

生成的HTML:

<div class="col-lg-8"> 
    <label for="PriceDate">Pricing Date</label> 
    <select data-val="true" data-val-number="The field PriceDate must be a number." data-val-required="The PriceDate field is required." id="PriceDate" name="PriceDate"><option value="">--New Pricing--</option> 
    <option value="2">1/4/2016 6:33 PM</option></select> 
</div> 

回答

1

即使在更改事件之前(专门针对DOM就绪事件),您正在读取所选下拉选项的值。因此,如果没有选项作为页面加载的一部分被预先选定(例如:创建页面 e),您将得到undefined作为$priceValue变量的值。

您应该阅读change事件代码内下拉列表中选定的选项值。

$(function(){ 

    $("#PriceDate").change(function() { 

     var $pID = { iD: $(this).val() }; 

     if ($(this).val()) { 
      $.ajax({ 
      type: "GET", 
      url: '@Url.Action("GetPrices", "Sales")', 
      data: $pID, 
      success: function (data) { 
       alert(data); 
       $("#Prices").val(data); 
      } 
     }); 
     } 
     else { 
     //clear data 
      $("#Prices").val(''); 
     } 
    }).change(); 

}); 

也请记住您当前的代码是呼吁降change()方法注册变更事件代码,在document ready后下来。这意味着在加载页面DOM之后总是会触发更改事件。我不确定这是故意的!

+1

这样做。我知道这很简单。非常感谢! – jle

+0

我正在研究这个,但是页面DOM加载后不会触发的影响是什么? – jle