2012-04-07 91 views
2

編輯: 看過我這樣做的方式後,我決定更改我的整個視圖模型,因此此問題已無效。我不介意知道我做錯了什麼,但我真的不需要我的項目的答案。MVC3 EditorFor()更改JavaScript模型中的值無法識別更改

謝謝!

當下拉列表的值發生變化時,我使用Javascript來更改文本框的值。當頁面發佈時,在Javascript中更改的值始終爲零。

JavaScript似乎工作正常,但價值並沒有回到服務器。

這裏是我的視圖模型:

... 
[Required(ErrorMessage = "\"{0}\" is required")] 
    [Display(Name = "Mileage Out")] 
    public decimal MileageOut { get; set; } 

[Required(ErrorMessage = "Vehicle is required.")] 
    public Guid VehicleID { get; set; } 

    [Display(Name = "Vehicle")] 
    public List<SelectListItem> Vehicles { get; set; } 
.... 

這是我的觀點:

.... 
<div class="editor-label"> 
     @Html.LabelFor(model => model.Vehicles, "Vehicle") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.VehicleID, new SelectList(Model.Vehicles, "Value", "Text"), "Vehicle is required . . .", new {@onchange="GetLastMileage(this.value);"}) 
     @Html.ValidationMessageFor(model => model.Vehicles) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.MileageOut) 
    </div> 
    <div class="editor-field"> 
     @Html.EditorFor(model => model.MileageOut, null, "txtMileageOut") 
     @Html.ValidationMessageFor(model => model.MileageOut) 
    </div> 
... 
<script type="text/javascript"> 

function GetLastMileage(vehicleID) { 
    switch (String(vehicleID)) 
    { 

     @{ 
      foreach (KeyValuePair<string, decimal> item in Model.VehiclesLastMileage) 
      { 
       @Html.Raw("case '" + item.Key + "': document.getElementById('txtMileageOut').value = '" + ((decimal)item.Value).ToString() + "';break;") 
      } 
     } 
     default: return 0; 
    } 
} 

</script> 

我發現,如果我改變了:

@Html.EditorFor(model => model.MileageOut, null, "txtMileageOut") 

這樣:

@Html.EditorFor(model => model.MileageOut) 

日期回到服務器正常,但JavaScript不起作用(文本框上沒有標識)。顯然,我使用錯誤的方法來更改客戶端上的值,但我不知道正確的方法。

謝謝!

回答

2

更改javascript。

document.getElementById('txtMileageOut').value 

document.getElementById('MileageOut').value 

此外,你應該使用jQuery和移動的JavaScript出自己的外部文件。它也會簡化JS代碼。你可以使用分類器來代替ID,並用更少的代碼做更多的事情。

+0

謝謝。當我回來時,我會試試這個。 – user1304444 2012-04-07 21:19:48

+0

這不起作用。 Firebug說:'document.getElementById(「MileageOut」)爲空' – user1304444 2012-04-08 02:41:10

+0

呈現的代碼是什麼(由瀏覽器看到)? – 2012-04-09 16:19:57