2017-07-14 116 views
0

我有一個MVC視圖,其中包含一年的下拉列表和一個提交按鈕。默認情況下,當前年份(即2017年)數據在頁面加載時加載,並且工作正常,但是當我從下拉列表中選擇其他年份時,它不刷新視圖。請參閱下面的代碼:刷新MVC查看按鈕點擊

HistoricData.cshtml

<div class="form-group"> 
      <label for="year">Year</label> 
      <select id="year" name="year" class="form-control"> 
       <option>2017</option>      
       <option>2016</option> 
       <option>2015</option> 
       <option>2014</option> 
       <option>2013</option> 
      </select> 
     </div> 
     <button id="btnData" class="btn btn-default" onclick="GetData()">Get Data</button> 

     <table id="tblData" class="table table-condensed table-striped"> 
     <thead> 
      <tr> 
       <th>ID</th> 
       <th>Name</th> 
       <th>Date/Time</th> 
      </tr> 
     </thead> 
     <tbody>  
      @foreach (var d in Model.AllData) 
      { 
       <tr> 
        <td>@d.ID</td> 
        <td>@d.Name</td> 
        <td>@d.DateTime</td>     
       </tr> 
      } 
     </tbody> 
    </table> 

腳本:

function GetData() { 
      $.ajax({ 
       type: "POST", 
       url: '@Url.Action("GetData")', 
       data: JSON.stringify({ 
        year: $("#year option:selected").text() 
       }), 
       contentType: "application/json; charset=utf-8"     
      }); 
     } 

控制器:HistoricDataController.cs

//this gets called on page load 
public ActionResult HistoricData() 
{ 
    var year = 2017; 
    return View(GetHistoricData(year));    
} 

//trying to call this method to refresh the data with the year selected 
public ActionResult GetData(int year) 
{ 
    var model = GetHistoricData(year); 
    return View("HistoricData", model); 
} 

private SomeData GetHistoricData(int year) 
{ 
    return SomeData; 
} 

回答

2

當您必須處理回覆時,您錯過了一個部分,因爲您可以在success上添加回調並將回覆(HistoricData視圖)添加到相關位置。另外,在你的情況最好使用GET而非POST

 $.ajax({ 
      type: "POST", 
      url: '@Url.Action("GetData")', 
      data: JSON.stringify({ 
       year: $("#year option:selected").text() 
      }), 
      contentType: "application/json; charset=utf-8", 
      success: function(data) { $("#somePlace").html(data); },     
     }); 
+0

而在你的控制器方法 –

+0

添加[httppost]標籤,並記住從這個動作返回'PartialView'而不是'View'。否則,您將在AJAX響應中呈現整個佈局。 –

+0

@ IIya.Sulimanov - 對不起,我忘了添加模型相關的細節,只是添加了代碼。 – user972255